-6

I have 6 numbers in array .

string[] list = { "1", "1", "2","2","1","3" };

I want result like this. please help.

"1" = 3
"2" = 2
"3" = 1

John Willemse
  • 6,608
  • 7
  • 31
  • 45
Saqi
  • 151
  • 2
  • 5
  • 12

2 Answers2

3
var itemCounts = list.GroupBy(l => l)
                     .Select(g => new { key = g.Key, count = g.Count()});
paul
  • 21,653
  • 1
  • 53
  • 54
1

Assuming your numbers in SearchArray >0. Here is an alternative approach

You can also write a function 1) find Max - One Loop

  for( int i=0;i<searchArray.length;i++){
    if (searchArray[i]>max) max=searchArray[i];
  }

2) Initialize an Array[Max+1]= 0

3) Loop thru each item and increment the size in Array

 for( int i=0;i<searchArray.length;i++){

     Array[searchArray[i]]++;
  }
aked
  • 5,625
  • 2
  • 28
  • 33
  • Why would one use this `O(n*n)` algorithm while Linq is shorter and **faster** – I4V Apr 11 '13 at 13:24
  • 1
    I4V, do you really understand how Linq work? I don't think using loop is slower. Loop is always the basic of everything related to processing list and IEnumerable stuff. – King King Apr 11 '13 at 13:25
  • @I4V i think this is not N^2 this is N+N right 2N so in Big O notation this N order right ? – aked Apr 11 '13 at 13:25
  • @KingKing, I guess *you* don't understand it. `GroupBy` uses HashSet internally which has `O(1)` complexity. @simplecoder, I though you used two nested loops, so forget my comment. – I4V Apr 11 '13 at 13:28
  • @I4V OK, if so, we can use HashSet for our collection and use loop outside without linq, however that's just an idea, I still love LINQ so much, but I also love the so-called loop in programming. :) – King King Apr 11 '13 at 13:31
  • 1
    @KingKing of course,.. – I4V Apr 11 '13 at 13:34