Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine object properties into a list with LINQ

Tags:

c#

linq

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.

like image 411
TesterTurnedDeveloper Avatar asked Dec 29 '22 06:12

TesterTurnedDeveloper


1 Answers

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);
like image 77
Kirk Woll Avatar answered Jan 13 '23 13:01

Kirk Woll