Pregunta

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

List<Foo> fooList;

¿Cómo consigo una lista de todos los identificadores de artículos referenciados en el interior fooList?

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();
¿Fue útil?

Solución

Uso SelectMany y tiene que devolver una lista concatenada de la PrimaryItem y OtherItems (si están presentes):

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

Otros consejos

Como una ligera variación:

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

Esto toma el conjunto de PrimaryItem, y (cuando se establece HasOtherItems) concatena el conjunto combinado de OtherItems. El Union asegura distinta.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top