Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为每个键返回不同的列表_C#_Linq_Group By - Fatal编程技术网

C# 为每个键返回不同的列表

C# 为每个键返回不同的列表,c#,linq,group-by,C#,Linq,Group By,我有一个表,它在代码中被解析为字符串[]的列表(每个字符串[]都是一列) 比如说: string[] column1 = { 0, 3, 5 } string[] column2 = { 1, 2, 2 }; string[] column3 = { 8, 3, 8 }; List<string[]> table = new List<string[]>() { column1, column2, column3 }; 它是这个,这个和简单1的混合体。 我考虑使用col

我有一个表,它在代码中被解析为字符串[]的列表(每个字符串[]都是一列)

比如说:

string[] column1 = { 0, 3, 5 }
string[] column2 = { 1, 2, 2 };
string[] column3 = { 8, 3, 8 };
List<string[]> table = new List<string[]>() { column1, column2, column3 };
它是这个,这个和简单1的混合体。 我考虑使用column1和column3创建一个对象,然后执行以下操作:

我的意思是,一些表达式不需要创建新类和填充对象列表。。。另外,我想作为输出

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

您可以使用扩展方法和来创建行,而不是仅为分组而创建新类型

那么分组就相当简单了。每个组都有一个表示第3列的键,
i分组
本身是一个
IEnumerable
,包含您仅从中选择第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

pescolino使用
Zip
的答案非常好。如果您不能使用它(例如,如果您不在.NET 4.x上),则可以使用
Select
的索引器重载生成所需的结果:

var res = col1.Select((fld,idx) => new { Field = fld, Index = idx })
          .GroupBy(entry => col3[entry.Index], entry => entry.Field)
          .Select(grp => grp.ToArray());

还要注意,你的问题应该问一个问题。你想知道什么?我怎么做。创建一个新类、一个对象列表,然后执行groupby,这看起来性能很差(而且不是一个好代码)。我认为selectmany操作比创建新类更好,但我不知道如何使用它。
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
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();
var res = col1.Select((fld,idx) => new { Field = fld, Index = idx })
          .GroupBy(entry => col3[entry.Index], entry => entry.Field)
          .Select(grp => grp.ToArray());