0

Does anybody know how I get and IEnumerable form the following query?

var neueLieferanten = Bestellpositionen.Where(x => x.SelectedArtikel is not null)
   .Select(x => x.SelectedArtikel)
   .Select(y => y.LieferantenArtikel.Select(x => x.Lieferant));

The first class has a property called SelectedArtikel which is another class which holds a List of LieferantenArtikel. Every one of this objects has an object called Lieferant which I need.

Marvin Klein
  • 1,436
  • 10
  • 33
  • 2
    Does this answer your question? [Flatten List in LINQ](https://stackoverflow.com/questions/1590723/flatten-list-in-linq) – gunr2171 Oct 13 '20 at 15:17

1 Answers1

0

From what you describe:

var neueLieferanten = Bestellpositionen.Where(bp => bp.SelectedArtikel != null)
  .SelectMany(bp => bp.SelectedArtikel.LieferantenArtikel) 
  .Select(la => la.Lieferant);

The SelectMany takes e.g. 10 List<LieferantenArtikel> inside 10 Bestellpositionen.SelectedArtikels and turns them into a single List of LieferantenArtikel, from which the Select then extracts the Lieferant property

You can structure it slightly differently for the same result:

var neueLieferanten = Bestellpositionen.Where(bp => bp.SelectedArtikel != null)
  .SelectMany(bp => bp.SelectedArtikel.LieferantenArtikel 
    .Select(la => la.Lieferant)
  );

I presented it this way to outline that really, the only change is the position of the bracket.. We're either turning a list of lists into a single list and then extracting a property, or we're extracting a property from a list in a list, and then turning it into a single list; use whichever way round appeals to your understanding more (I prefer the former)

Caius Jard
  • 72,509
  • 5
  • 49
  • 80