Compare two Lists for differences

前端 未结 5 997
逝去的感伤
逝去的感伤 2020-11-27 13:04

I would like some feedback on how we can best write a generic function that will enable two Lists to be compared. The Lists contain class objects and we would like to iterat

5条回答
  •  北海茫月
    2020-11-27 13:18

    I think you're looking for a method like this:

    public static IEnumerable CompareSequences(IEnumerable seq1,
        IEnumerable seq2, Func comparer)
    {
        var enum1 = seq1.GetEnumerator();
        var enum2 = seq2.GetEnumerator();
    
        while (enum1.MoveNext() && enum2.MoveNext())
        {
            yield return comparer(enum1.Current, enum2.Current);
        }
    }
    

    It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

    This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

    Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

    // Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
    var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
    int index;    
    
    foreach(var element in results)
    {
        Console.WriteLine("{0:#000} {1}", index++, element.ToString());
    }
    

提交回复
热议问题