0

I have a list of string, in this list there are some strings which are duplicated twice or more.

I want to count them and add them to dictionary like this:

List<string> lst = { 'A' , 'B' , 'B' , 'c' , 'c' , 'c' };

and it goes to dictionary like this :

A , 1
B , 2
c , 3

How can I do this ?!

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Amir Hossein
  • 229
  • 2
  • 4
  • 14

2 Answers2

3
var dict = lst.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());

If you want to do it in a case insensitive way

var dict = lst.GroupBy(x => x, StringComparer.InvariantCultureIgnoreCase )
              .ToDictionary(x => x.Key, x => x.Count());
Eser
  • 12,031
  • 1
  • 19
  • 32
1

Something like this:

  List<Char> lst = new {  // Note "Char"
    'A' , 'B' , 'B' , 'c' , 'c' , 'c' };

  var dictionary = list
    .GroupBy(item => item)
    .ToDictionary(chunk => chunk.Key,
                  chunk => chunk.Count());
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199