Search code examples
c#.netlinq

Compare two lists on a condition and add to another list


Having two lists. First one is IEnumerable<dynamic> and other one is normal list. Need to compare them and on a certain condition I need to add them to new lists.

NormalList:

{
"List" :
{
"OuterID" : 1111,
"Name" : "Apple",
"Country" : "USA",
"InnerList" :{
              "InnerId" : 2222
             }
},
{
"OuterID" : 5555,
"Name" : "Mango",
"Country" : "INDIA",
"InnerList" :{
              "InnerId" : 7777
             }
}

Other list is IEnumerable<dynamic> received from db call

Resultlist
{
"OuterID" : 5555,
"InnerId" : 7777
}

Need to compare if the OuterID and InnerId are same. If yes, add them to MatchingList else add them to unmatching list

I have tried in simple C# like below. Is it possible to query using Linq to make it easier.

foreach(var list in NormalList)
{
int count = 0;
foreach(var res in ResultList)
{
 if(list.OuterID == (int)res.OuterID && list.InnerList.InnerId == (int)res.InnerId)
  {
      matchinglist.Add(list);
      count++;
  }
}
if(count == 0)
    unmatchinglist.Add(list);
}

Solution

  • You can replace the first loop by Where and the second by Any:

    var matchinglist = NormalList.Where(
        n => ResultList.Any(r => n.OuterID == (int)r.OuterID && r.InnerList.InnerId == (int)r.InnerId)
    ).ToList();
    var unmatchinglist = NormalList.Except(matchinglist).ToList();
    

    As unmatchinglist is NormalList without the matching element. Except is a good fit here.