List array duplicates with count

后端 未结 7 1969
孤街浪徒
孤街浪徒 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:32
    Hashtable ht = new Hashtable();
    foreach (string s in inputStringArray)
    {
        if (!ht.Contains(s))
        {
            ht.Add(s, 1);
        }
        else
        {
            ht[s] = (int)ht[s] + 1;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 09:33

    a little error above, right code is:

    string[] arr = { "red", "red", "blue", "green", "Black", "blue", "red" };
    
    var results = from str in arr
                  let c = arr.Count( m => str.Contains(m.Trim()))
                  select str + " count=" + c;
    
    foreach(string str in results.Distinct())
        Console.WriteLine(str);
    
    0 讨论(0)
  • 2020-11-30 09:41

    make another array of counts ....and loop on the original array putting a condition that if it found red increment the 1st cell of the count array ...if it found blue increment the second cell in the count array ....etc. Good Luck .

    0 讨论(0)
  • 2020-11-30 09:47

    Hmm That is a very hard task, but Captain Algorithm will help you! He is telling us that there are many ways to do this. One of them he give me and I give it to you:

    Dictionary <object, int> tmp = new Dictionary <object, int> ();
    
    foreach (Object obj in YourArray)
      if (!tmp.ContainsKey(obj))
        tmp.Add (obj, 1);
     else tmp[obj] ++;
    
    tmp.Values;//Contains counts of elements
    
    0 讨论(0)
  • 2020-11-30 09:52

    Add them to a Dictionary:

    Dictionary<string, int> counts = new Dictionary<string, int>();
    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.

    0 讨论(0)
  • 2020-11-30 09:53

    LINQ makes this easy:

    Dictionary<string, int> counts = array.GroupBy(x => x)
                                          .ToDictionary(g => g.Key,
                                                        g => g.Count());
    
    0 讨论(0)
提交回复
热议问题