Linq nested list expression

2019-01-26 06:33发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-26 07:13

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!

查看更多
Anthone
3楼-- · 2019-01-26 07:21
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....

查看更多
登录 后发表回答