C
C#ā€¢3y ago
Becquerel

Idiomatic LINQ way to access both object and an object's property? [Answered]

var list = new List<string>();

foreach (Item item in items)
{
foreach (string thing in item.Things)
{
list.Add($"{thing} + {item.OtherProperty}");
}
}

return list;
var list = new List<string>();

foreach (Item item in items)
{
foreach (string thing in item.Things)
{
list.Add($"{thing} + {item.OtherProperty}");
}
}

return list;
I'd like to do this with LINQ. Normally I would use .Select(), but if the inner operation needs both an object (item) and an inner property (thing), I don't know of a clean way to do it. I can .Select() into a tuple containing both items, but this is really ugly. Any idea?
7 Replies
Tvde1
Tvde1ā€¢3y ago
IIRC SelectMany has a ResultSelector, can you access the parent there?
Becquerel
BecquerelOPā€¢3y ago
i see - let me try that
Tvde1
Tvde1ā€¢3y ago
in your case:
var list = items.SelectMany(item => item.Things.Select(thing => $"{thing} + {item.OtherProperty}"));
var list = items.SelectMany(item => item.Things.Select(thing => $"{thing} + {item.OtherProperty}"));
Becquerel
BecquerelOPā€¢3y ago
that does look like pretty much it - awesome! thanks very much šŸ˜„
Tvde1
Tvde1ā€¢3y ago
You're welcome ^^
Accord
Accordā€¢3y ago
āœ… This post has been marked as answered!
Want results from more Discord servers?
Add your server