Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare list anonymous type to another list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading