Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query a List of objects containing a list of object

Tags:

c#

linq

I have a list of foo 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've pieced together the above linq query, but crepes.item throws an error. "List does not contain a definition for 'item' and no definition for 'item' accepting first argument...

like image 798
Chris Avatar asked Dec 30 '15 15:12

Chris


People also ask

Can we use LINQ on list in C#?

How to query an ArrayList with LINQ (C#) This example uses LINQ to query over an ArrayList in C#. You must declare the type of the range variable to reflect the type of the objects in the collection.

What type of objects can you query using LINQ?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

Is any variable that stores a query instead of the results of a query?

In LINQ, a query variable is any variable that stores a query instead of the results of a query. More specifically, a query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach statement or a direct call to its IEnumerator.

Which of the following can serve as a data source for a LINQ query in C#?

Types such as ArrayList that support the non-generic IEnumerable interface can also be used as a LINQ data source.


1 Answers

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

var item = crepes.Where(a => a.item.Any(x => x.doritos == "coolRanch")).FirstOrDefault();
like image 130
Vlad274 Avatar answered Nov 03 '22 01:11

Vlad274