本文介绍了为每个键返回不同的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,该表在代码中被解析为string []的列表(每个string []是一列).

I have a table that is parsed in code as a List of string[] (each string[] is a column).

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.

I want to select a column (i.e. Column1) groupby Column3, and create a list with each different value in Column3. In other words: group Column1 by column3 and create a Column for each different value of Column3.

输出为:

string[] result1 = { 3 };  // From column3[1] = 3
string[] result2 = { 0, 5 };  // From column3[0] = column3[2] = 8

这是帖子的混合,此和 msdn .我考虑创建带有column1和column3的对象,然后执行此发布:

It´s a mix of this post, this one, and Simple 1 from msdn.I think about creating a object with column1 and column3, and then do as this 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());

但是此代码有点丑陋.不会有类似的东西

But this code code is a bit ugly. Isn´t there something like

column3.selectmany(...).GroupBy(row => row.row3).ToDictionary(grp => grp.Key, grp => grp.ToList());

我的意思是,某些表达式无需创建新类并填充对象列表...而且,我想要作为输出

I mean, some expression without the need of creating a new class and fill a list of objects... Also, I want as output

string[] result1 = { 3 };  // From column3[1] = 3
string[] result2 = { 0, 5 };  // From column3[0] = column3[2] = 8

推荐答案

您可以使用 Zip 扩展方法和 anonymous type 创建行.

Instead of creating a new type just for grouping you can use the Zip extension method and an anonymous type to create the rows.

分组非常简单.每个组都有一个代表column3的键,而IGrouping本身就是一个IEnumerable,其中包含仅从中选择列1的行:

Grouping is pretty straightforward then. Each group has a key which represents column3 and the IGrouping itself is an IEnumerable containing the rows from which you select only column 1:

var rows = column1.Zip(column3, (c1, c3) => new
{
    Column1 = c1,
    Column3 = c3
});

var output = from row in rows
             group row by row.Column3 into groupedRows
             select groupedRows.Select(r => r.Column1).ToArray();

这将产生一个IEnumerable<string[]>.

这篇关于为每个键返回不同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:00