Reputation: 12107
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
Upvotes: 2
Views: 3916
Reputation: 494
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() );
}
Upvotes: -1
Reputation: 1351
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);
Upvotes: 2
Reputation: 32266
Just slap a ToDictionary
after a GroupBy
.
var counts = List.GroupBy(l => l)
.ToDictionary(grp => grp.Key, grp => grp.Count());
Upvotes: 5