Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am new to LINQ, here is my question:
I have a List of a class, an item which is present in only one List (ItemID), and a List of List. I know how to check if the ItemID exists in the list, but I don't know how to check if the it exists in the List of List. Here is my code to check if the item exists in a list:

List<MyClass> list = new List<MyClass>;
List<List<MyClass>> Lists= new List<List<MyClass>>();
If (List.Exists(x => x.ItemID == itemIndicator.ItemID))


Please, I would like to check the ItemID in the Lists instead of List.

What I have tried:

I tried:

C#
If (Lists.Exists(x => x.ItemID == itemIndicator.ItemID))


But it shows an error because the ItemID belongs to the list, not to the List of List.
Posted
Updated 24-Mar-18 1:29am

C#
<pre>if(lists.SelectMany(x => x).ToList().Exists(y => y.ItemID == itemIndicator.ItemID))
 
Share this answer
 
Comments
Clifford Nelson 27-Apr-18 7:47am    
Why do you have the ToList(). Should not need that.
Pushkar Prabhu 14-May-18 11:56am    
SelectMany<t> returns IEnumerable<t>. We can not use Exists on IEnumerable<t>. It is available only on List<t>. So i have used ToList<t> to convert IEnumrable<t> to List<t>.
Richard Deeming 15-May-18 13:44pm    
It would be much more efficient to use Any:
lists.SelectMany(x => x).Any(y => y.ItemID == itemIndicator.ItemID)

Or the alternative that Griff posted in solution 1.
Pushkar Prabhu 18-Nov-18 14:06pm    
any should be used instead of Exists.
Exists works on List<t> where as Any works on IEnumerable<t>.
Try:
If (Lists.Exists(x => x.Exists(y => y.ItemID == itemIndicator.ItemID)))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900