2011-11-02 154 views
2

我有三個列表兩份名單,BeforeList,AfterList和FinalList比較使用LINQ

BeforeList具有以下值

ID Description Operation 
1 Descr1  Null 
2 Descr2  Null 
3 Descr3  Null 

AfterList具有以下值

ID Description Operation 
1 Descr1  Null 
2 DescrC  Null 
4 Descr4  Null 

我FinalList會

ID Description Operation 
1 Descr1  Null 
2 DescrC  Update 
3 Descr3  Delete 
4 Descr4  Add 

如何獲得FinalList使用LINQ

+10

你嘗試過什麼嗎? –

+0

BeforeList和AfterList之間有什麼關係。身份證上有鑰匙嗎? –

+1

爲什麼* DescrC *是'Update'而* Descr1 *是'null'? – user7116

回答

3

如何像:

var beforeListById = beforeList.ToDictionary(item => item.Id); 
var afterListById = afterList.ToDictionary(item => item.Id); 

var finalResult = from id in beforeListById.Keys.Union(afterListById.Keys) 

        let before = beforeListById.ContainsKey(id) ? beforeListById[id] : null 
        let after = afterListById.ContainsKey(id) ? afterListById[id] : null 

        select new Record 
        { 
         Id = id, 
         Description = (after ?? before).Description, 
         Operation = (before != null && after != null) 
            ? (after.Description == before.Description ? "Null" : "Update") 
            : (after != null) ? "Add" : "Delete" 
        }; 

編輯地:查詢簡單(假設項目都是非空)。

+0

謝謝,完美地工作...... – Gansun

1

這是一個簡單的實現,但你可以嘗試這樣的事:

var differences = listA.Where(a => !listB.Any(b => b.id == a.id)).Union(listB.Where(b => !listA.Any(a => a.id == b.id))); 

編輯

根據MSDN,你可以只使用Union合併這兩個列表,並且默認情況下會將重複項過濾掉。如果不是,您可以隨時致電Distinct()

List<Something> = beforeList.Union(afterList).ToList();