【发布时间】:2015-08-19 11:31:03
【问题描述】:
我有以下简化输入:
List<string[]> sList = new List<string[]>();
sList.Add(new string[]{ "Product", "ProductID"});
sList.Add(new string[] { "Fork", "1" });
sList.Add(new string[] { "Spoon", "2" });
sList.Add(new string[] { "Knife", "3" });
我想要以下输出
ResultList[0] == { "Product" ,"Fork","Spoon","Knife"};
ResultList[1] == { "ProductID" ,"1","2","3"};
首先我用 2 个循环解决了这个问题,然后我改变了我对这个 linq 的方法(两者都工作):
List<string[]> Result = sList.SelectMany(x => x)
.Select((x, index) => new KeyValuePair<int, string>(index % sList.First().Length, x))
.GroupBy(s => s.Key).Select(g => g.Select(x => x.Value)
.ToArray()).ToList();
它有效,但对我来说似乎有点迂回。有没有我忽略的更简单的方法(内置?)?
【问题讨论】:
-
对于像
new {new String[] {"1", "2"}, new String[] {"A"}, new String[] {"3", "4", "5"}};这样的锯齿状数据,您希望得到什么结果?你想如何表示一个hole,即“2”hole“4”? -
@DmitryBychenko - 所有行的列数总是相等的 - 你可以依赖
-
试试这个:
var result = new List<string[]> { sList.Select(x => x[0]).ToArray(), sList.Select(x => x[1]).ToArray() }; -
您要查找的操作通常称为transpose。见this example。