Question

class Foo
{
    int PrimaryItem;
    bool HasOtherItems;
    IEnumerable<int> OtherItems;
}

List<Foo> fooList;

Comment puis-je obtenir une liste de tous ids objet référencé dans fooList?

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();
Était-ce utile?

La solution

Utilisez SelectMany et ont le retourner une liste concaténée de la PrimaryItem et OtherItems (si elles sont présentes):

var result = fooList
    .SelectMany(f => (new[] { f.PrimaryItem })
        .Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
    .Distinct();

Autres conseils

Comme une légère variation:

var items = fooList.Select(i => i.PrimaryItem).Union(
      fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));

Cela prend l'ensemble des PrimaryItem, et (où HasOtherItems est défini) concatène l'ensemble combiné de OtherItems. Le Union assure distinct.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top