比较/更新两个列表

时间:2012-10-12 22:05:09

标签: c# c#-4.0

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

所以,我正在寻找一种比较两个列表并使用合并结果创建第三个列表的优雅方法。

示例:

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"
    }]

下一个问题是在不重新散列原始内容的情况下散列新答案。但是,我相信我能解决这个问题。我只是在寻找一种优雅的方式进行合并。

感谢。

1 个答案:

答案 0 :(得分: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);
}