我在分组列表方面遇到了困难。这就是我所拥有的;
First column => second column
1 => 3,4
2 => 3,4
3 => 3,4,5
5 => 3,4
6 => 3,4,7
7 => 3,4
8 => 3,4,5
9 => 3,4,5
在我的程序中,第一列是Objects,第二列中的每一列也是Object List。所以First Column(Object)有一个IList
我要做的是检索具有完全相同的第二列的第一列组;像这样,
(the numbers are of the first column, I don't need the second column values)
1,2,5,7 one group
3,8,9 one group
6 one group
但我找不到一种有效的方法来做到这一点。我试过Linq,但我不太了解它。
答案 0 :(得分:2)
简单地说,这是GroupBy
表达式,可以执行您想要的操作:
var group = myList.GroupBy(
x => String.Join("|",x.SecondColumn),
x => x.FirstColumn);
通过SecondColumn
中所有项目的串联进行分组,但选择FirstColumn
作为群组。
测试代码:
var myList = new List<MyObject>(){
new MyObject{ FirstColumn = 1, SecondColumn = new List<int>{3,4}},
new MyObject{ FirstColumn = 2, SecondColumn = new List<int>{3,4}},
new MyObject{ FirstColumn = 3, SecondColumn = new List<int>{3,4,5}},
new MyObject{ FirstColumn = 5, SecondColumn = new List<int>{3,4}},
new MyObject{ FirstColumn = 6, SecondColumn = new List<int>{3,4,7}},
new MyObject{ FirstColumn = 7, SecondColumn = new List<int>{3,4}},
new MyObject{ FirstColumn = 8, SecondColumn = new List<int>{3,4,5}},
new MyObject{ FirstColumn = 9, SecondColumn = new List<int>{3,4,5}}
};
var group = myList.GroupBy(x => String.Join("|",x.SecondColumn), x => x.FirstColumn);
foreach(var i in group)
Console.WriteLine( String.Join(",",i));
输出
1,2,5,7
3,8,9
6
实例:http://rextester.com/RFWLB54456
评论后修改:您可以更改GroupBy
行以对SecondColumn
的元素进行排序:
var group = myList.GroupBy(
x => String.Join("|",x.SecondColumn.OrderBy(n => n),
x => x.FirstColumn);