How to get lists of X and Y from a list of points using a single linq query?

Go To


I'm generating List<int> x and List<int> y from List<Point> p using this code:

List<int> x = (from a in p select a.X).ToList();
List<int> y = (from a in p select a.Y).ToList();

So is there any single LINQ query for getting x and y from p?

2012-04-04 04:54
by ahmadali shafiee
In your example the two lists are assigned to two different variables. Are you asking if that's possible in a single query, or are you asking if you can generate a single list with both the X and Y values - Matt Hamilton 2012-04-04 04:57
If the former, no you cannot. If the later, just select a - Eric J. 2012-04-04 04:58
You could return a Tuple, List> from your quer - Fox32 2012-04-04 04:59
I dont see the Point ;p (pun intended - leppie 2012-04-04 05:06
Ok, I don't think a tuple of lists work, but for each should work in every situation - Fox32 2012-04-04 05:15
What have you tried?Omar 2012-04-04 09:28
@leppie:System.Drawing.Point - ahmadali shafiee 2012-04-04 19:27
@Fuex:I want to create x and y using single linq query - ahmadali shafiee 2012-04-04 19:28


No but you can do something like this:

var tuples = p.Select(x => new Tuple<int, int>(x.X, x.Y)).ToList();

But i think that the best solution remains this, using two queries:

List<int> x = (from a in p select a.X).ToList();
List<int> y = (from a in p select a.Y).ToList();
2012-04-04 12:49
by Omar


You basically can't, but you can fool yourself:

public static class LinqEx
    public static void ToLists<T, T1, T2>(this IEnumerable<T> source, SelectorDst<T, T1> selectorDst1, SelectorDst<T, T2> selectorDst2)

public class SelectorDst<T, TList>
    public readonly List<TList> List;
    public readonly Func<T, TList> Selector;

    public SelectorDst(List<TList> list, Func<T, TList> selector)
        this.List = list;
        this.Selector = selector;

... Some place in the code

var points = new List<Point>();
var xs = new List<int>();
var ys = new List<int>();

points.ToLists(new SelectorDst<Point, int>(xs, p => p.X),
               new SelectorDst<Point, int>(ys, p => p.Y));
2012-04-04 05:19
by SimpleVar