AddRange / funzionalità concat all'interno di una lambda espressione Select
Domanda
class Foo
{
int PrimaryItem;
bool HasOtherItems;
IEnumerable<int> OtherItems;
}
List<Foo> fooList;
Come faccio a ottenere un elenco di tutti gli ID voce fa riferimento all'interno fooList
?
var items = fooList
.Select(
/*
f => f.PrimaryItem;
if (f.HasOtherItems)
AddRange(f => f.OtherItems)
*/
).Distinct();
Soluzione
Usa SelectMany
e farlo ritornare una lista concatenata del PrimaryItem
e OtherItems
(se presenti):
var result = fooList
.SelectMany(f => (new[] { f.PrimaryItem })
.Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
.Distinct();
Altri suggerimenti
Come una leggera variazione:
var items = fooList.Select(i => i.PrimaryItem).Union(
fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));
Questa operazione richiede l'insieme di PrimaryItem
, e (dove HasOtherItems
è impostato) concatena l'insieme combinato di OtherItems
. Il Union
assicura distinto.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow