2012-10-12 98 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