It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                已关闭8年。
            
                    
我有三个列表,BeforeList,AfterList和FinalList

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


如何使用LINQ获取FinalList

最佳答案

怎么样:

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


编辑:使查询更简单(假设项目为非null)。

09-26 11:05