Home > Software engineering >  How to compare list anonymous type to another list
How to compare list anonymous type to another list

Time:02-16

I am trying to use Except to compare two list but one is an anonymous type.

For Example:

 var list1 = customer.Select(x => new { x.ID, x.Name }).ToList();
 var list2 = existcustomer.Select(x => x.ID).ToList();

And I trying to compare two list IDs and return a list of list one name.

My code:

var checkIfCustomerIdNotExist = list1.Where(x => x.ID.ToList().Except(list2)).Select(x =>  x.Name).ToList();

I am wondering if there is any workaround.

CodePudding user response:

I'd advise using a dictionary instead of a List

//create a dictionary of ID to name
var customerDict = customer.ToDictionary(x => x.ID, x => x.Name); 
//get your list to compare to
var list2 = existcustomer.Select(x => x.ID).ToList(); 
//get all entries where the id is not in the second list, and then grab the names
var newNames = customerDict.Where(x => !list2.Contains(x.Key)).Select(x => x.Value).ToList(); 

In general it's good to think about what data structure suits your data the best. In your case list1 contains a list of tuple where ID needs to be used to find Name - using a data structure more suited to that (A dictionary) makes solving your problem much easier and cleaner

Note, the solution assumes ID is unique, if there are duplicate IDs with different names you might need a Dictionary<string, List< string >> instead of just a Dictionary<string,string> - but that would probably require more than just a single line of linq, code would be fairly similar though

  •  Tags:  
  • c#
  • Related