如何使用单个linq查询从点列表中获取X和Y的列表?

时间:2012-04-04 04:54:38

标签: c# linq linq-to-objects

我使用以下代码从List<int> x生成List<int> yList<Point> p

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

那么从x获取yp是否有任何单一的LINQ查询?

2 个答案:

答案 0 :(得分:2)

不,但你可以这样做:

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

但我认为最好的解决方案仍然是这个,使用两个查询:

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

答案 1 :(得分:0)

你基本上不能,但你可以欺骗自己:

public static class LinqEx
{
    public static void ToLists<T, T1, T2>(this IEnumerable<T> source, SelectorDst<T, T1> selectorDst1, SelectorDst<T, T2> selectorDst2)
    {
        selectorDst1.List.AddRange(source.Select(selectorDst1.Selector));
        selectorDst2.List.AddRange(source.Select(selectorDst2.Selector));
    }
}

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));