Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq nested list expression

please I need your help with a Linq expression:

I have nested objects with lists, this is how the main object hierarchy looks like (each dash is an atribute of the sub-class):

Folder
-name
-List<Subfolder> Subfolders
                 -name
                 -List<Document> Documents
                                 -name
                                 -key

Having this hierarchy of objects, I have a Document name, and I want to search for it and return its parent folder (Subfolder)

Example:

Folder
    -name: Customer
    -List<Subfolder> Subfolders
                     -name: Personal
                     -List<Document> Documents
                                     -name: Resume
                                     -key : 1

If I said: "Resume", the linq expression should return me: the subfolder "Personal" (the object).

Please help me, because of the two nested lists I'm having troubles, with one it'll be easy.

Thanks in advance.

like image 884
lidermin Avatar asked May 26 '11 20:05

lidermin


People also ask

How do you sort a list with Linq using nested property?

OrderBy(b => b. Author. OrderBy(a => a.Name)). ToList();

How do you use SelectMany?

SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.

What is Linq in C# with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


2 Answers

folders
    .SelectMany(s => s.SubFolders)
    .FirstOrDefault(s => s.Documents.Any(d => d.Name == "Resume"));

I'm shooting from the hip here but I think that should work....

like image 173
BFree Avatar answered Sep 27 '22 20:09

BFree


That's easy:

var folders = ...;

var subfolders =
    from folder in folders
    from subfolder in folder.Subfolders
    where subfolder.Documents.Any(d => d.Name == "Resume")
    select subfolder;

Think LINQ!

like image 21
Steven Avatar answered Sep 27 '22 21:09

Steven