2016-05-26 43 views
0

重复的项目我在这个列表下方获取从列表中<T>

string cellValue; 
String cellAddress; 

和采样值给出模型的列表是:

cellValue ="txt" ; CellAddres="A1"; 
cellValue ="txt" ; CellAddres="A2"; 
cellValue ="txt" ; CellAddres="A3"; 
cellValue ="txt" ; CellAddres="B1"; 
cellValue ="num" ; CellAddres="B2"; 
cellValue ="num" ; CellAddres="B3"; 
cellValue ="num1" ; CellAddres="B4"; 
cellValue ="txt1" ; CellAddres="C3"; 

我要的是创造所有重复值的列表 像后处理应该有两个列表从这个数据产生

1) cellValue ="txt" ; CellAddres="A1"; 
    cellValue ="txt" ; CellAddres="A2"; 
    cellValue ="txt" ; CellAddres="A3"; 
    cellValue ="txt" ; CellAddres="B1"; 

2) cellValue ="num" ; CellAddres="B2"; 
    cellValue ="num" ; CellAddres="B3"; 
+1

什么'cellValue = “NUM1”'和'cellValue = “txt1中”' - 他们为什么从你期望的输出不见了? – Jamiec

+1

我想 - 他们没有在样本列表上重复多次,所以只是跳过它们,只处理那些重复的样本。 –

回答

2

一般情况下,你想要做的是你原来的列表中cellValue。这会给你一个IGrouping<string,YourObject>

var result = list.GroupBy(x => x.cellValue); 

这会给你4个结果(txtnumtxt1 & num1作为键)。每个分组是IEnumerable<YourObject>,所以你可以列举每个组,就好像它是它自己的列表。

如果您想排除那些只有1个孩子的群组,您可以在Where内使用Count()

var result = list.GroupBy(x => x.cellValue) 
       .Where(g => g.Count() > 1); 

这将只有您指定的2个组作为您的输出。

活生生的例子:http://rextester.com/RSN67321

1

是似乎想要GroupBy(),这样的事情:

List<MyItem> source = ... 

var result = source 
    .GroupBy(item => item.cellValue) 
    .Where(chunk => chunk.Count() > 1) // duplicates 
    .Select(chunk => String.Join("; ", chunk));