Building a dictionary of counts of items in a list

后端 未结 5 1356
广开言路
广开言路 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: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 countingList = new Dictionary();
    
       void Add( string s )
       {
            if( countingList.ContainsKey( s ))
                 countingList[ s ] ++;
            else
                countingList.Add( s, 1 );
       }
    }
    

提交回复
热议问题