2015-02-10 58 views
1

我希望能夠獲取列表中某些類型的事物的百分比。使用LINQ獲取列表中的TypeOf項目的百分比

說我有動物名單,但名單裏面我有貓,狗和蛇:

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()。

任何想法?

+0

被告知;到目前爲止,所有發佈的答案都包含可能的零除異常。 – Stefan 2015-02-10 10:18:15

回答

4

你最那裏的方式

,你可以簡單地做:

var catPercent = list.OfType<Cat>().Count()/(float)list.Count(); 
+0

當我嘗試它時,仍然返回0。 – user3113376 2015-02-10 09:49:31

+0

將整數除以更大的整數將始終爲0. – sloth 2015-02-10 09:56:20

+0

我想明白了。我遇到了漂浮物的鑄造問題。 – user3113376 2015-02-10 10:00:26

1

GroupBy就是你所需要的。它創建具有共同密鑰的項目組,在您的情況下是類的類型。使用該分組上的選擇將允許您創建一個具有您希望獲得的百分比的元組。

animals.GroupBy(a => a.GetType()).Select(group => new Tuple<Type, double>(group.Key, group.Count()/animals.Count())); 
8

不,我認爲你根本不需要使用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 
         }); 
+0

我不太明白你在做什麼在這裏得到CountsByType。你能否更深入地解釋一下? – user3113376 2015-02-10 09:51:19

+0

@ user3113376:我不確定你的意思。你瞭解'countByType'部分嗎?我之後做的所有事情是將每一個數除以動物的總數,以得到每種類型的比例...... – 2015-02-10 09:58:40