开发者

Combine object properties into a list with LINQ

开发者 https://www.devze.com 2023-01-19 08:58 出处:网络
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.

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 quer开发者_高级运维y 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);


This is an example where I would probably use query syntax with LINQ:

var result = from item in someList
             let values = new int[]{ item.A, item.B, item.C, ... }
             from x in values
             select x;

Using a custom iterator (as Kirk demonstrates) may be more efficient, since it doesn't require allocating the temporary array - but the CLR is relatively good at recycling short-lived objects, so in practice this is rarely an issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号