Difference between two List

后端 未结 1 584
青春惊慌失措
青春惊慌失措 2020-12-31 19:56

Can I use a fancy LINQ query to return a List, by passing it in a method (List oldList, List newList

相关标签:
1条回答
  • 2020-12-31 20:27

    Given an IEqualityComparer for FileInfo shown below:

    public class FileInfoEqualityComparer : IEqualityComparer<FileInfo>
    {
        public bool Equals(FileInfo x, FileInfo y)
        {
            return x.FullName.Equals(y.FullName);
        }
    
        public int GetHashCode(FileInfo obj)
        {
            return obj.FullName.GetHashCode();
        }
    }
    

    You can use following code to find the difference between two lists:

    var allItems = newList.Union(oldList);
    var commonItems = newList.Intersect(oldList);
    var difference = allItems.Except(commonItems, new FileInfoEqualityComparer());
    

    To find items added to newList list, use following code:

    var addedItems = newList.Except(oldList, new FileInfoEqualityComparer());
    
    0 讨论(0)
提交回复
热议问题