简体   繁体   中英

Comparing Two lists of Different Objects without for loop

I have two lists:

List<ObjA> AList;
List<ObjB> BList;

Now I have a method to compare individual Obj A to Obj B :

void CompareObjAToObjB(ObjA a, ObjB b)
{
   ....
}

where it asserts the individual elements of objects by comparing them. For now, I did by sorting the two lists using an unique identifier and then iterate the sorted list through a for loop and calling the Compare method.

Is there a better way to compare the lists using a Lambda expression or Linq?

Edit

ok. Here is My original code..

 Alist.sort((x,y) => string.Compare(x.acctNumber, y.acctNumber));
 Blist.sort((x,y) => string.Compare(x.acctNumber, y.acctNumber));

 for(int i =0; i< Alist.count; i++)
 {
      CompareObjAToObjB(Alist[i], Blist[i]);
 }

Alist contains the repo Object that I input where as BList is a Object that returns by a Service API call. Both contains the same data but in different structures.

Assuming you want to find all items with the same identifier you could use Join :

var inBoth = from a in AList
             join b in BList
             on a.UniqueIdentifier equals b.UniqueIdentifier 
             select new { a, b };

foreach(var ab in inBoth)
    Console.WriteLine("A:{0} B:{1}", a.ToString(), b.ToString()); // if ObjA  and ObjB have a meaningful ToString

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