【发布时间】:2013-03-05 01:23:25
【问题描述】:
我有一个在代码中被解析为字符串 [] 列表的表格(每个字符串 [] 都是一列)。
Column1| Column2 | Column3
--------+---------+----------
0 | 1 | 8
3 | 2 | 3
5 | 2 | 8
让我们说:
string[] column1 = { 0, 3, 5 }
string[] column2 = { 1, 2, 2 };
string[] column3 = { 8, 3, 8 };
List<string[]> table = new List<string[]>() { column1, column2, column3 };
我想通过 Column3 分组选择一列(即 Column1),并在 Column3 中创建一个包含每个不同值的列表。换句话说:将 Column1 按 column3 分组,并为 Column3 的每个不同值创建一个 Column。
输出将是:
string[] result1 = { 3 }; // From column3[1] = 3
string[] result2 = { 0, 5 }; // From column3[0] = column3[2] = 8
这是post、one 和 msdn 中的 Simple 1 的混合体。 我想用column1和column3创建一个对象,然后像这样post:
Class Row { public Row(string row1, string row3); }
List<Row> rows = new List<Row>();
for(int i = 0; i < column1.Length; i++)
{ rows.Add(new Row(Column1[i], Column3[i])); }
var output = rows.GroupBy(row => row.row3).ToDictionary(grp => grp.Key, grp => grp.ToList());
但是这段代码代码有点难看。有没有类似的东西
column3.selectmany(...).GroupBy(row => row.row3).ToDictionary(grp => grp.Key, grp => grp.ToList());
我的意思是,一些表达式不需要创建一个新类并填充一个对象列表......另外,我想要作为输出
string[] result1 = { 3 }; // From column3[1] = 3
string[] result2 = { 0, 5 }; // From column3[0] = column3[2] = 8
【问题讨论】:
-
还要注意你的问题应该问一个问题。你想知道什么?
-
我该怎么做。创建一个新的类,一个对象列表,然后做groupby 似乎性能很差(而且代码不是很好)。我认为 selectmany 操作会比创建新类更好,但我不知道如何使用它。