Linq nested list expression

please i need your help with Linq expression:

I have nested objects with lists, here is what the main hierarchy of objects looks like (each dash is an attribute of a subclass):

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

Having this hierarchy of objects, I have the name of the document, and I want to search for it and return the 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 to me: the β€œPersonal” subfolder (object).

Please help me, because of the two nested lists I am having problems, with one it will be easy.

Thanks in advance.

+7
source share
2 answers
 folders .SelectMany(s => s.SubFolders) .FirstOrDefault(s => s.Documents.Any(d => d.Name == "Resume")); 

I take off my thigh here, but I think it should work ...

+10
source

This is 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!

+10
source

All Articles