2014-11-21 20 views
1

工作。我也想了解他們的指數查找重複和VS 2010 C#</p> <p>我有如下數組,我試圖尋找是否有數組中重複 索引號

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

該代碼產生了什麼,您希望如何改變它? – CodeCaster 2014-11-21 16:25:53

+0

@shamim - 你有機會看我的答案嗎? – 2014-11-23 09:09:55

回答

-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,但它足以開始。

+0

對於那些倒票的人,我只是想表明代碼的功能風格比命令風格簡單得多。 – 2014-11-21 17:36:01

+0

這不是我的失望,但你的解決方案不會產生作者在他的例子中顯示的內容。在數組末尾添加另一個「紅色」,您將得到相同數量的結果(3)。但他只想分組連續的項目。在他期望的結果中,他有兩次'紅' – 2014-11-21 17:55:00

+0

是的,你是對的。我會盡力更新答案。 – 2014-11-21 18:17:55

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

這將產生具有你其作爲重複字符串鍵(它存在> 1)和它的價值指數的在a列表的列表的字典。

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

Complete Working Fiddle Here

+0

Rahul Singh,謝謝你的回覆。你的語法令人難以置信,但我對擴展方法process.thanks再次感謝 – shamim 2014-12-04 12:03:48