I’m trying to flatten out a simple class that has a parent + child array, into a single class.
From:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<PewPew> PewPews { get; set; }
}
public class PewPew
{
public string Name { get; set; }
public string Whatever { get; set; }
}
- 1 | Fred | { { AAA | xxx }, { BBB | yyy } }
- 2 | Bill | { { CCC | zzz } }
To:
public class FooProjection
{
public int Id { get; set; }
public string Name { get; set; }
public PewPewName { get; set; }
public PewPewWhatever { get; set; }
}
- 1 | Fred | AAA | xxx
- 1 | Fred | BBB | yyy
- 2 | Bill | CCC | zzz
The pure Linq approach
You can use the
SelectMany()overload that allows you to specify a result selector that is called on every element in the collection:This approach is the most concise, but takes some time getting used to, especially if you have not been working with Linq a lot.
Edit:
As per @AS-CII’s comment it might be more readily understandable (and this is important for maintaining the code base) to just use a loop and a simple projection with
Select(). If someone has a problem with Linq in this scenario at all, two nested loop would do as well. I’ll show both for completeness.Using a foreach loop and a Select projection
Just iterate over all Foos and create a new
FooProjectionfor eachPewPewin the current item. Add all of them to thefooProjectionslist that is in scope. This approach uses a Linq projection to map from eachPewPewto aFooProjection, using thefoofrom the foreach loop.Using two nested foreach loops
Just use two
foreachloops, the outer iterating over the Foos, the inner over the PewPews collection in the current foo – add a newFooProjectionto thefooProjectionslist that is in scope. This approach does not make use of Linq at all.