List array duplicates with count

后端 未结 7 1968
孤街浪徒
孤街浪徒 2020-11-30 09:06

I have an array which contains the following results

red 
red
red
blue
blue
Green
White
Grey

and I want to get duplicate count of every val

7条回答
  •  有刺的猬
    2020-11-30 09:52

    Add them to a Dictionary:

    Dictionary counts = new Dictionary();
    foreach(string s in list) 
    {
       int prevCount;
       if (!counts.TryGet(s, out prevCount))
       {
          prevCount.Add(s, 1);
       }
       else
       {   
           counts[s] = prevCount++;
       }
    }
    

    Then counts contains the strings as keys, and their occurence as values.

提交回复
热议问题