Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two list and return not matching items using linq

Tags:

c#

list

linq

c#-4.0

i have a two list

List<Sent> SentList; List<Messages> MsgList; 

both have the same property called MsgID;

MsgList            SentList    MsgID Content      MsgID Content Stauts 1       aaa        1       aaa     0 2       bbb        3       ccc     0 3       ccc         4       ddd 5       eee 

i want to compare the MsgID in Msglist with the sentlist and need items which are not in the sent list using linq

Result   MsgID Content 2       bbb 4       ddd 5       eee 
like image 410
Spen D Avatar asked Aug 14 '12 17:08

Spen D


People also ask

Can LINQ Select return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer. Show activity on this post.

Does LINQ Select return new object?

While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.

Can we compare two lists in C#?

By using Intersect , we can check which elements in source list are also contained in compare list. var source = new List<string>() { "a", "b", "c" }; var compare = new List<string>() { "b", "c", "d" }; var result = source. Intersect(compare);


2 Answers

You could do something like:

HashSet<int> sentIDs = new HashSet<int>(SentList.Select(s => s.MsgID));  var results = MsgList.Where(m => !sentIDs.Contains(m.MsgID)); 

This will return all messages in MsgList which don't have a matching ID in SentList.

like image 102
Reed Copsey Avatar answered Sep 16 '22 19:09

Reed Copsey


The naive approach:

MsgList.Where(x => !SentList.Any(y => y.MsgID == x.MsgID)) 

Be aware this will take up to m*n operations as it compares every MsgID in SentList to each in MsgList ("up to" because it will short-circuit when it does happen to match).

like image 44
lc. Avatar answered Sep 18 '22 19:09

lc.