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

本文关键字:列表 获取 单个 何使用 linq 查询 | 更新日期: 2023-09-27 18:29:51

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

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

那么,从p中获取xy是否有任何单一的LINQ查询?

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

没有,但你可以这样做:

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

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

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