我使用以下代码从List<int> x
生成List<int> y
和List<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
获取y
和p
是否有任何单一的LINQ查询?
答案 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));