简体   繁体   English

如何检索要列出的不同值的总和?

[英]How do I retrieve a sum of distinct values to list?

The SQL table and model supporting my application is very similar to what I have displayed below. 支持我的应用程序的SQL表和模型与我在下面显示的非常相似。

Id | CustomerName | FruitName | Charge
_____________________________________
1  | Bob          | Banana    | 3.00 
2  | Jill         | Apple     | 2.00
3  | Bob          | Apple     | 3.00
4  | Marvin       | Banana    | 1.00
5  | Sam          | Pear      | 4.00

[Key]
public int Id {get; set;}
public string CustomerName { get; set; }
public string FruitName { get; set;}
public string Charge {get; set;}

What I would like to do is pull the distinct FruitName and the Charge.Sum() and display it ToList() in my view. 我想要做的是拉出不同的FruitNameCharge.Sum()并在我的视图中显示它ToList() Here is what I have tried 这是我尝试过的

var fruitToList = (from f in db.fruit select f).ToList();    
var test = fruitToList.GroupBy(x => x.FruitName).Sum(y => y.Charge).Select(z => z.First());
return View(test.ToList());

I know that the reason why it does not work is because Charge needs to be something like decimal.Parse(y.Charge) but I cannot figure out how to do it within the Sum() function. 我知道它不起作用的原因是因为Charge需要像decimal.Parse(y.Charge)但我无法弄清楚如何在Sum()函数中做到这一点。 Should I be going about this a different way? 我应该采取不同的方式吗?

Weird that the charge is a string, but never the less, since the data is already in a list you can group by fruit name extract the charge as a decimal and sum the group 奇怪的是,收费是一个字符串,但从来没有那么少,因为数据已经在一个列表中,你可以按水果名称分组提取费用作为小数并对组进行求和

For example 例如

//...

var test = fruitToList
    .GroupBy(_ => _.FruitName, _ => new { Charge = decimal.Parse(_.Charge) })
    .Select(g => new Fruit {
        FruitName = g.Key,
        Charge = g.Sum(f => f.Charge).ToString()
    });

//...

Which could also be simplified even more 这也可以进一步简化

var test = fruitToList
    .GroupBy(_ => _.FruitName, _ => decimal.Parse(_.Charge))
    .Select(g => new Fruit {
        FruitName = g.Key,
        Charge = g.Sum().ToString()
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM