查找数组中的重复项及其索引号

时间:2014-11-21 16:23:16

标签: c# arrays linq

开展vs 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()};

3 个答案:

答案 0 :(得分:0)

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

这将生成一个字典,其密钥为重复字符串(存在&gt; 1),其值为a列表中的索引列表。

答案 1 :(得分:0)

您可以使用GroupAdjacent编写的here扩展方法。从question获取此参考。您的查询将变得非常简单: -

var result = colors.Select((v, i) => new { Value = v, Index = i })
                               .GroupAdjacent(x => x.Value)
                               .Select(x => new
                               {
                                   Color = x.Key,
                                   Count = x.Count(),
                                   Index = x.First().Index
                               });

完成工作小提琴Here

答案 2 :(得分:-2)

这是最后的工作:

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

Debug View of Program

这样的东西

from a in AS
from b in Enumerable.Range(0,AS.Conunt()-1)
into (a,b)
group by a

然后,您可以通过计算每个组长度轻松地将计数添加到结果中。

我没有视觉工作室,也没有记住LINQ的好记忆,但这就足够了。