如何在Linq的单个查询中使用Distinct()和Sum() [英] How to Use Distinct() and Sum() in Single Query in Linq

查看:116
本文介绍了如何在Linq的单个查询中使用Distinct()和Sum()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有2列,例如 ID,数量.我想在LINQ中获得不同的ID及其数量总和. 我这样尝试过

Here I have 2 Columns like Id,Quantity. I want get the Distinct Id and its Quantity Sum in LINQ. I tried like this

var r = list.Where(some operation)
            .Select(x => x.Id)
            .Distinct()
            .Select(x => (int?)x.Quantity))
            .Sum();

在x.Quantity,我遇到了错误..我该如何解决.. 请提出您的建议

Here at x.Quantity I got error..how can I solve this.. please give your suggestions

推荐答案

如果我假设Id为int且Quantity为字符串,那么也可以使用聚合.下面是一个示例:

If I assume that Id is int and Quantity is string, then you can use aggregate also. Below is one example:

class TestClass
{
    public int I { get; set; }
    public string S { get; set; }
}

class Program
    {
        static void Main()
        {
            var myclass = new TestClass[]
            {
                new TestClass {I = 1, S = "1"}, new TestClass { I = 1, S = "11" }, new TestClass { I = 1, S = "111" },
                new TestClass {I = 2, S = "2"},new TestClass {I = 2, S = "222"},new TestClass {I = 2, S = "2"},
                new TestClass {I = 3, S = "3"},new TestClass {I = 3, S = "333"},new TestClass {I = 3, S = "33"},
                new TestClass {I = 4, S = "44"},new TestClass {I = 4, S = "4"},
                new TestClass {I = 5, S = "5"}
            };

            var filteredObject = myclass.GroupBy(x => x.I).Select(y => new
            {
                I = y.Key,
                S = y.Select(z => z.S).Aggregate((a, b) => (Convert.ToInt32(a) + Convert.ToInt32(b)).ToString())
            });

            filteredObject.ToList().ForEach(x => Console.WriteLine(x.I + "    " + x.S));
        }

    }

结果就像:

1 123

2 226

3 369

4 48

5 5

按任意键继续. .

希望有帮助.

这篇关于如何在Linq的单个查询中使用Distinct()和Sum()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆