Linq select to new object

前端 未结 6 1908
攒了一身酷
攒了一身酷 2020-12-09 07:45

I have a linq query

var x = (from t in types select t).GroupBy(g =>g.Type)

which groups objects by their type, as a result I want to ha

6条回答
  •  轮回少年
    2020-12-09 08:18

    If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

    var types = new[] {typeof(string), typeof(string), typeof(int)};
    var x = types
            .GroupBy(type => type)
            .ToDictionary(g => g.Key, g => g.Count());
    foreach (var kvp in x) {
        Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
    }
    Console.WriteLine("string has a count of {0}", x[typeof(string)]);
    

提交回复
热议问题