c# - 使用 LINQ 获取列表中 TypeOf 项目的百分比

标签 c# linq

我希望能够获得列表中某些类型事物的百分比。

假设我有一个动物列表,但在该列表中我有猫、狗和蛇:

List<Animal> animals = new List<Animal>{
new Cat { Name="Cuddles", Sound=Sound.Meow, Age=3 },
new Dog { Name="Spot", Sound=Sound.Bark, Age=7 },
new Cat { Name="Karma", Sound=Sound.Meow, Age=10 },
new Snake { Name="Nagini", Sound=Sound.Hiss, Age=1 },
new Dog { Name="Sparky", Sound=Sound.Bark, Age=4},
new Cat { Name="Matty", Sound=Sound.Meow, Age=15}
};

我希望能够获得这些动物的百分比,因此可能的结果集将是:

Cats: 0.50
Dogs: 0.35
Snakes: 0.15

但我不太确定如何获得这种类型的结果集。特别是如果我只想获得猫的百分比。

我知道我需要使用 list.OfType<Cat>()拉出只有猫的列表,但这也是我无法获得猫的百分比的时候,因为我不能使用 .Sum() 或 .Average()。

有什么想法吗?

最佳答案

不,我认为您不需要使用 OfType<>根本。我怀疑你真的想要GroupBy :

var countsByType = animals.GroupBy(x => x.GetType(),
                                   (t, g) => new { Type = t, Count = g.Count() });

这会给你:

{ Type = Cat, Count = 3 },
{ Type = Dog, Count = 2 },
{ Type = Snake, Count = 1 }

如果需要,您可以通过将计数除以总数来得出比例。例如:

var countsByType = animals.GroupBy(x => x.GetType(),
                                   (t, g) => new { Type = t, Count = g.Count() })
                          .ToList();
// Could just use animals.Count, but this approach works for sequences
// which can only be enumerated once.
var totalCount = countsByType.Sum(t => t.Count);
var proportions = countsByType.Select(pair => new { 
                            pair.Type,
                            Proportion = pair.Count / (double) totalCount
                        });

关于c# - 使用 LINQ 获取列表中 TypeOf 项目的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428348/

相关文章:

c# - 使用 JSON.net 将内部数组反序列化为对象

c# - 使用 Linq Dynamic 进行分组

c# - 使用动态 LINQ(或泛型)查询/筛选 Azure 表

c# - 如何使用 Foreach 遍历集合来构建 XDocument?

c# - C# .NET 窗体中的红绿指示灯

c# - 使用 Ninject 将通用接口(interface)绑定(bind)到存储库时获取 "MissingMethodException: Cannot create an instance of an interface"

c# - 关于ServiceStack.Redis的一些问题

c# - Linq 查询优化

c# - Entity Framework linq orderby 函数

c# - 在 WPF 窗口中显示时间