Youngjae
Youngjae

Reputation: 25060

Linq nested select query and result has same structure with selected items

I stucked to write a nested query with Select or SelectMany.

Let's take the traditional nested list that:

Sheet has Title fields
SheetDetail has Employee fields

Each Sheet has multiple SheetDetails as a master-detail manner.

I would like to make the result as below.

From below data...

Sheet   - SheetDetail
"A Sheet"-{"jane","herry","tom"}
"B Sheet"-{"kane","brown","jane"}
"C Sheet"-{"annie","ralph"}

To the result as below that has only 'jane' but maintain same master-detail structure.

Sheet   - SheetDetail
"A Sheet"-{"jane"}
"B Sheet"-{"jane"}

I tried

sheet.SelectMany(s => s.SheetDetails.Where(d => d.Description.Contains("jane")));

but as we can imagine, it gives wrong result.

How can I make it? please help-

Upvotes: 1

Views: 106

Answers (2)

cuongle
cuongle

Reputation: 75316

You can use Any to check:

Sheet.Where(s => s.SheetDetails.Any(d => d.Description == "jane")))
    .Select(s => new Sheet {
            Description = s.Description,
            SheetDetails = s.SheetDetails.Where(d => d.Description == "jane")
        });

Upvotes: 3

Ilya Ivanov
Ilya Ivanov

Reputation: 23636

if you want to have exactly one SheetDetail in result, you can create anonymous object like:

sheet
  .Where(s => s.SheetDetails.Any(d => d == "jane"))
  .Select(s => new {Sheet = s, SheetDetail == s.SheetDetails.First(d => d == "jane")});

Upvotes: 1

Related Questions