tags:

views:

51

answers:

2

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.

+3  A: 

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);
Kirk Woll
+2  A: 

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.

LBushkin
this does look interesting
TesterTurnedDeveloper
It's no more powerful yet dramatically more verbose than the OP's original example...
Kirk Woll
@Kirk: I don't disagree. However, I would say that expressing queries *as queries* can be useful. Depending on how it's used, `SelectMany` can obscure what the intent of the logic behind awkward lambda syntax.
LBushkin
@LBushkin, heh, yeah, though from where I sit, LINQ obscures the intent of the logic behind ackward query syntax. ;) But I realize this gets into religious warfare-zone, so I'll stop.
Kirk Woll