2012-10-12 74 views
0

我有一个场景,我们正在保存登录安全问题和答案列表。在保存答案之前,我们正在为安全性做单向散列。现在,我必须通过广告功能接受对此问题和答案列表的更新。我将收到一个列表,其中包含一个列表,其中包含包含问题和答案的列表。这个新列表将被拆散,我需要创建一个最终列表,其中包含未更改的问题和答案以及最新的列表。比较/更新两个列表

因此,我正在寻找比较两个列表并创建第三个与合并结果的优雅方式。

例子:

 
Original list: 

    "securityAnswers" : [{ 
     "question" : 1, 
     "answer" : "dfkldlfndajfdkghfkjbgakljdn" 
    }, { 
     "question" : 2, 
     "answerHash" : "ndlknfqeknrkefkndkjsfndskl" 
    }, { 
     "question" : 5, 
     "answerHash" : "ieruieluirhoeiurhoieubn" 
    }] 

Update list: 

    "securityAnswers" : [{ 
     "question" : 4, 
     "answer" : "answer to question 4" 
    }, { 
     "question" : 2, 
     "answerHash" : "" 
    }, { 
     "question" : 5, 
     "answerHash" : "new answer to question 5" 
    }] 

Merged list: 


    "securityAnswers" : [{ 
     "question" : 4, 
     "answer" : "answer to question 4" 
    }, { 
     "question" : 2, 
     "answerHash" : "ndlknfqeknrkefkndkjsfndskl" 
    }, { 
     "question" : 5, 
     "answerHash" : "new answer to question 5" 
    }] 

下一个问题将被散列的新的答案,而无需重新散列原件。但是,我相信我可以解决这个问题。我只是在寻找一种优雅的方式来进行合并。

谢谢。

回答

2

您可以使用LINQ。 Enumerable.Except返回设定的差值。因此,你需要创建一个自定义IEqualityComparer<Question>

public class QuestionComparer : IEqualityComparer<Question> 
{ 
    public bool Equals(Question x, Question y) 
    { 
     return x.Question == y.Question; // assuming that it's a value type like ID (int) 
    } 

    public int GetHashCode(Question obj) 
    { 
     return obj.Question.GetHashCode(); 
    } 
} 

现在你可以使用比较器:

var comparer = new QuestionComparer(); 
var newQuestions = UpdateList.Except(OriginalList, comparer).ToList(); 
var both = from o in OriginalList 
      join u in UpdateList on o.Question equals u.Question 
      select new { o, u }; 
var updatedQuestions = new List<Question>(); 
foreach(var x in both) 
{ 
    // modify following accordingly, i take the updated question if the hash contains something, otherwise i use the original question 
    if(x.u.AnswerHash != null && x.u.AnswerHash.Length != 0) 
     updatedQuestions.Add(x.u); 
    else 
     updatedQuestions.Add(x.o); 
} 
+0

很不错的。谢谢! – RockyMountainHigh