![](/img/trans.png)
[英]C#, Finding duplicates in arrays, Index was outside the bounds of the array
[英]Finding duplicates in an array and its index number
与2010 C#一起工作
我有以下数组,我试图查找数组中是否存在重复项。 我也想找出他们的索引
red
red
Grey
Grey
red
blue
blue
Green
White
Grey
我想获得数组的每个值的重复计数,例如:
red Count=2 index=0 (contain the duplicate cluster start index)
Grey Count=2 index=2
red Count=1 index=4
blue Count=2 index=5
Green Count=1 index=6
White Count=1 index=7
Grey Count=1 index=8
帮助我修复波纹管语法,以完全满足上述结果
var result = from p in a //a is the list
group p by p into g
select new { value=g.Key,count=g.Count()};
var dupl = new Dictionary<string, List<int>>();
var d = a.Distinct();
for (int i = 0; i < d.Count; ++i)
{
int match = 0;
for (int j = 0; j < a.Count; ++j)
{
if (a[j] == d[i])
{
++match;
if (++match > 1)
{
if (dupl.ContainsKey(d[i])) dupl[d[i]].Add(j);
else
{
dupl.Add(d[i], new List<int>());
dupl[d[i]].Add(j);
}
}
}
}
}
这将产生你有它的重复字符串键(它存在> 1),其值在索引列表的字典a
列表。
这是最后的工作:
namespace ConsoleApplication1
{
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var AS = new[] { "red", "red", "Grey", "Grey", "blue" };
var zippedList = AS.Zip(Enumerable.Range(0, AS.Length), (s, i) => new { s, i });
var finalResult =
from a in zippedList
group a by a.s into g
select new { key = g.Key, result = new { list = g.Select(o => o.i).ToList(), count = g.Count() } };
foreach (var item in finalResult)
{
Console.WriteLine(item.key);
Console.WriteLine(item.result.count);
Console.WriteLine(item.result.list);
}
Console.ReadLine();
}
}
}
像这样的东西
from a in AS from b in Enumerable.Range(0,AS.Conunt()-1) into (a,b) group by a
然后,您可以通过计算每个组的长度轻松地将计数添加到结果中。
我没有Visual Studio,也没有足够的记忆力来记住LINQ,但是从一开始就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.