从多个列表中选择重复项

时间:2013-09-01 18:23:49

标签: list linq duplicates linq-group

我有一个List<int>数组,我正在使用LINQ(感谢这个论坛),找到重复项,但在将列表合并到一个列表后,我该如何检索这样的字典:

KEY -> duplicate value | VALUE -> list index where duplicate was found

其实我这样做:

List<int> duplicates = hits.GroupBy(x => x)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();

猜猜我应该使用SelectMany

2 个答案:

答案 0 :(得分:3)

您可以将每个元素映射到(item,index),然后很容易为每个键选择受影响的索引。

var duplicates = hits.Select((item, index) => new {item, index})
    .GroupBy(x => x.item)
    .Where(g => g.Count() > 1)
    .Select(g => new {Key = g.Key, Indexes = g.ToList().Select(x => x.index)})
    .ToList();

答案 1 :(得分:2)

首先,你向你的元素“添加”一个索引,指示它们属于哪个列表,它们合并所有列表,最后你使用与你的代码类似的东西。

var query = arr.Select((x,i) => x.Select(y=>new{Elem = y, Index = i}))
    .SelectMany(x=>x)
    .GroupBy(x => x.Elem)
    .Where(x => x.Count() > 1)
    .ToDictionary(x => x.First().Elem, y => y.Select(z => z.Index).ToList());

主要区别在于如何创建字典,因为您必须构建找到重复项的索引列表。

举个例子,在这个输入上:

List<int>[] arr = new List<int>[3];
arr[0] = new List<int>() { 1, 2, 3 };
arr[1] = new List<int>() { 1 };
arr[2] = new List<int>() { 1, 3 };

你得到:

[1, {0,1,2}]
[3, {0,2}]
相关问题