Say I have properties num1, num2, num3 on objectX. I want to take a list of objectX and create a single list of integers populated with the num1, num2, num3 values.
Here's an example using System.Drawing.Point:
Point p1 = new Point(1,2);
Point p2 = new Point(3,4);
var points = new[] { p1, p2 };
var combined = points.SelectMany(a => new[] {a.X, a.Y});
Is this the most readable way of doing this? The syntax feels a bit fiddly to me. Could you do it with a LINQ Query expression?
FYI using LBushkin's query expression in this example would look like this:
var combined = from p in points
let values = new[] {p.X, p.Y}
from x in values
select x;
I'll leave it an exercise for the reader to decide which is more readable.
I think cleanest would be if ObjectX had a property to combine your num properties, let's call it Numbers:
public IEnumerable<int> Numbers
{
get
{
yield return Num1;
yield return Num2;
yield return Num3;
}
}
Now whenever you have acecss to an ObjectX, you can easily interrogate it's number properties, allowing you to do:
var combined = objectXs.SelectMany(a => a.Numbers);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With