问题
I have an array of List<int>
, I'm using LINQ (thanks to this forum), to find duplicates, but after merging lists into one list, how can I retrieve a dictionary like this :
KEY -> duplicate value | VALUE -> list index where duplicate was found
Actually I'm doing this :
List<int> duplicates = hits.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
Guess I should use SelectMany
回答1:
You can map every element to (item, index) and then it will be easy to selected impacted indexes for each key.
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();
回答2:
First of all you "add" to your elements an index indicating which list they are a part of, they merge all of them, and lastly you use something similar to your code.
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());
The main difference is how you create the dictionary, since you have to build the list of indices where your duplicates are found.
As an example, on this input:
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 };
you get :
[1, {0,1,2}]
[3, {0,2}]
来源:https://stackoverflow.com/questions/18561472/select-duplicates-from-multiple-lists