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
  • 732,580
  • 175
  • 1,330
  • 1,459
Amir Hossein
  • 249
  • 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,346
  • 1
  • 22
  • 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
  • 180,369
  • 20
  • 160
  • 215