我希望能够获得列表中某些类型事物的百分比。
假设我有一个动物列表,但在该列表中我有猫、狗和蛇:
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/