Linq query a List of objects containing a list of objects

I have a foo list called crepes. I want to return foo, where bar.doritos == "coolRanch"

 class foo { List<bar> item; string candy; string beer; } class bar { string doritos; string usb; } var item = crepes.item.Where(x => x.doritos == "coolRanch").FirstOrDefault(); 

From other threads, I linked the above linq request, but crepes.item throws an error. "The list does not contain a definition for" item "and a definition for" item "that takes the first argument ...

+5
source share
3 answers

Given that crepes is a List<Foo> , you need to add an extra layer to the linq query.

 var item = crepes.Where(a => a.item.Any(x => x.doritos == "coolRanch")).FirstOrDefault(); 
+11
source

Your item access modifier is private (this is C # by default for class ), it should be made public

This applies to your doritos too

Also, since your crepes is a List , add another LINQ layer (also suggested by others) to completely fix it, something like this

 var item = crepes.Where(f => f.item.Any(b => b.doritos == "coolRanch")).FirstOrDefault(); //f is of foo type, b is of bar type 
+3
source

If you fix your classes as follows

 class Foo { public List<Bar> Items { get; set; } public string Candy { get; set; } public string Beer { get; set; } } class Bar { public string Doritos { get; set; } public string Usb { get; set; } } 

Your request will look like

 var crepes = new List<Foo>(); var item = crepes.FirstOrDefault(f => f.Items.Any(b => b.Doritos == "coolRanch")); 

Here we are trying to get the first Foo that has at least one Bar in Items , where Doritos == "coolRanch" .

+2
source

Source: https://habr.com/ru/post/1239499/


All Articles