Building a dictionary of counts of items in a list

后端 未结 5 1357
广开言路
广开言路 2021-01-02 06:08

I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count

相关标签:
5条回答
  • 2021-01-02 06:43

    One idea would be to give the dictionary a default value of zero, so you wouldn't have to special case the first occurrence.

    0 讨论(0)
  • 2021-01-02 06:44

    I would have made a specialized List, that backed by the Dictionary and the add method would test for membership and increase count if found.

    sorta like:

    public class CountingList
    {
        Dictionary<string, int> countingList = new Dictionary<string, int>();
    
       void Add( string s )
       {
            if( countingList.ContainsKey( s ))
                 countingList[ s ] ++;
            else
                countingList.Add( s, 1 );
       }
    }
    
    0 讨论(0)
  • 2021-01-02 06:48
    Dictionary<string, int> a = stuff.GroupBy(p => p).OrderByDescending(r=>r.Count()).ToDictionary(q => q.Key, q => q.Count());
    

    You can GroupBy and then create dictionary to count each group. As performance test indicate, usually there are more efficient approaches other than Linq. I think your code is more efficient, while Linq solution is more readable and beautiful.

    0 讨论(0)
  • 2021-01-02 06:57

    Well, there isn't really any better way to do it.

    Perhaps you could write a LINQ query that would group the strings and then count how many strings there are in each group, but that would not be nearly as efficient as what you already have.

    0 讨论(0)
  • 2021-01-02 07:05

    You can use the group clause in C# to do this.

    List<string> stuff = new List<string>();
    ...
    
    var groups = 
        from s in stuff
        group s by s into g
        select new { 
            Stuff = g.Key, 
            Count = g.Count() 
        };
    

    You can call the extension methods directly as well if you want:

    var groups = stuff
        .GroupBy(s => s)
        .Select(s => new { 
            Stuff = s.Key, 
            Count = s.Count() 
        });
    

    From here it's a short hop to place it into a Dictionary<string, int>:

    var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
    
    0 讨论(0)
提交回复
热议问题