简体   繁体   中英

Compare two lists of custom objects by a specified method C#

I know questions with same title have been asked before, but this is my case:

I want to compare two lists of custom objects which do not override Equals nor they implement IEqualityComparer but I want to compare them against a static comparison method like:

public class Custom
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

public static bool Compare(Custom A, Custom B)
{
    return A.Prop1 == B.Prop1 && A.Prop2 == B.Prop2;
}

Assuming that the lists have the elements in same order:

List<Custom> l1 = new List<Custom> {new Custom { Prop1 = "A", Prop2 = "B"}, new Custom { Prop1 = "A", Prop2 = "B" } };
List<Custom> l2 = new List<Custom> { new Custom { Prop1 = "A", Prop2 = "B" }, new Custom { Prop1 = "A", Prop2 = "b" } };

I am trying to avoid a for like this:

if(l1.Count != l2.Count)return;
for (int i = 0; i < l1.Count; i++)
{
    if(!Compare(l1[i], l2[i]))return;
}
bool comparisonResult = true;

using linq, but I guess I am missing something:

bool comparisonResult = l1.Any(x => l2.Any(y => Compare(x, y)));

This is what have tried, but it keeps returning true when lists are not the same.

If you must use LINQ and don't want to implement an IEqualityComparer for Custom ...

Assuming the two lists are in the proper sequence, you can make use of Zip to create a new list with each item side-by-side, kind of like a Tuple . You can then call All on that new list to call your static Compare method:

  List<Custom> l1 = new List<Custom> {new Custom { Prop1 = "A", Prop2 = "B"}, new Custom { Prop1 = "A", Prop2 = "B" } };
  List<Custom> l2 = new List<Custom> { new Custom { Prop1 = "A", Prop2 = "B" }, new Custom { Prop1 = "A", Prop2 = "b" } };

  bool comparisonResult = l1.Zip(l2, (x, y) => new { x, y }).All(z => Compare(z.x, z.y));

You can use All

bool comparisonResult = l1.All(x => l2.Any(y => Compare(x, y)));

This will return true only if all the items in l1 match the inner condition - which is that they exist in the l2. This is an easier to read way that applying "not" twice.

This will not solve the case of duplicated items in lists so you can:

  1. Distinct the lists
  2. Do in the inner function a Where and count equals to 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM