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
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.
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.
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);
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With