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

后端 未结 3 1808
借酒劲吻你
借酒劲吻你 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:28

    If you're looking for a general, language-agnostic solution, then you're looking for some kind of data synchronization of ordered lists. The basic algorithm would be:

    i1 = 0
    i2 = 0
    while (i1 < list1.size && i2 < list2.size)
    {
      if (list1[i1] < list2[i2])
      {
        //list1[i1] is not in list2
        i1++
      }
      else if (list1[i1] > list2[i2])
      {
        //list2[i2] is not in list1
        i2++
      }
      else
      {
        //item is in both lists
        i1++
        i2++
      }
    }
    if (i1 < list1.size)
       //all remaining list1 items are not in list2
    if (i2 < list2.size)
       //all remaining list2 items are not in list1
    
    0 讨论(0)
  • 2021-02-13 13:37

    Can you use Linq:

    List<ListItem> list1 = GetYourList1();
    List<ListItem> list2 = GetYourList2();
    var diff = list1.Except(list2);
    

    Your example specific:

    var diff = newList.Except(existingList);
    

    Not sure if it is the most efficient but it's concise :)

    0 讨论(0)
  • 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<ListItem> CompareLists(List<ListItem> existingList, List<ListItem> newList)
    {
        List<ListItem> mergedList = new List<ListItem>();
        mergedList.AddRange(newList);
        mergedList.AddRange(existingList.Except(newList, new ListItemComparer()));
        return mergedList.OrderByDescending(x => x.Score).Take(10).ToList();
    }
    
    public class ListItemComparer : IEqualityComparer<ListItem>
    {
        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);
    
    0 讨论(0)
提交回复
热议问题