What is the most efficient pattern/algorithm to compare two lists and find the delta between those two lists?

后端 未结 3 1816
借酒劲吻你
借酒劲吻你 2021-02-13 12:46

We have two lists, let\'s say students and their scores. I want to compare these two lists and find the delta between the new list and the old list, then find the least intrusi

3条回答
  •  梦如初夏
    2021-02-13 13:49

    This should be able to do the trick if you don't have the same name twice in your list. In your example, you have 2x Steve, but you need a way to distinct between them.

    public static List CompareLists(List existingList, List newList)
    {
        List mergedList = new List();
        mergedList.AddRange(newList);
        mergedList.AddRange(existingList.Except(newList, new ListItemComparer()));
        return mergedList.OrderByDescending(x => x.Score).Take(10).ToList();
    }
    
    public class ListItemComparer : IEqualityComparer
    {
        public bool Equals(ListItem x, ListItem y)
        {
            return x.Name == y.Name;
        }
    
        public int GetHashCode(ListItem obj)
        {
            return obj.Name.GetHashCode();
        }
    }
    

    You can call it like this:

    newList = CompareLists(existingList, newList);
    

提交回复
热议问题