从多个列表中选择重复项 [英] Select duplicates from multiple lists

查看:150
本文介绍了从多个列表中选择重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

其实我在这样做:

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

猜猜我应该使用 SelectMany

推荐答案

您可以将每个元素映射到(项目,索引),然后轻松选择每个键的受影响的索引。

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();

这篇关于从多个列表中选择重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆