从列表中计算百分比?

时间:2016-06-10 17:46:00

标签: c# linq

我有以下csv数据

2,1,3,5,0 3,1,3,20,0 4,1,6,200,1000

我无法有效地计算百分比。以下是我到目前为止的情况:

var csvParser = new CsvParser();
var customers = csvParser.ParseCsv(@"data.csv");

var results = from c in customers
              let total = customers.Sum(x => x.Stake)
              let totalWin = customers.Sum(x => x.Win)
              group  c by new
              {
                  Id=c.Id,
                  Stake=c.Stake,
                  Win=c.Win,
              } into history
              select new
              {
                  Id = history.Key.id,
                  percentage = (float)history.Count() / (float)e.Key.total
              };

return results;

1 个答案:

答案 0 :(得分:2)

你已经过度复杂了。我假设你混合了那些利益相关的东西,因为这是另一个查询的一部分,而且let是完全没必要的。

您只需按ID分组,然后将group.Count(of Win)除以group.Count()以获得胜利百分比。

var cheaters = customers.GroupBy(c => c.Id)
    .Select(g => new 
    { 
          Id= g.Key, 
          Percentage = g.Count(c => c.Win > 0) / (double)g.Count()
          // feel free to aggreate other values here like g.Sum(x => x.Stake)
    })
    .Where(c => c.Percentage >= .6);