简体   繁体   中英

group and count duplicates to a dictionary with linq

with the following list:

a
a
b
b
b
c

I would like to make, using linq, a dictionary that contains:

a => 2
b => 3
c => 1

for now I have:

var Q = (from l in List
        group l by l into g
        let Count = g.Count()
        select new { Key = g.Key, Value = Count})

How do I turn this to a dictionary?

Edit: I changed the last line to:

select new Dictionary<string, int> { g.Key, Count });

but I still don't have the right syntax

Just slap a ToDictionary after a GroupBy .

var counts = List.GroupBy(l => l)
    .ToDictionary(grp => grp.Key, grp => grp.Count());

You are very close to solution in fact. You can also solve it such;

    var query =
        from q in list
        group q by q into t
        select new
        {
            Key = t.Key,
            Value = t.Count()
        }; 
    var dict = query.ToDictionary(x => x.Key, x => x.Value);

This way Works to me

List<string> vs = new List<string> { "a", "a", "b", "a", "b", "b" };

        var output = vs.GroupBy(word => word).OrderByDescending(group => group.Count()).Select(group => group.Key);

        foreach (var item in output)
        {
            Console.WriteLine(item + "=>" + item.Count() );
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM