如何在Linq中的单个查询中使用Distinct()和Sum()

时间:2015-07-17 07:21:27

标签: linq c#-4.0

这里我有2个列 编号,数量。我希望在LINQ中获得Distinct Id及其数量总和。  我试过这个

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

这里是x.Quantity我收到错误..我可以解决这个问题.. 请提出你的建议

2 个答案:

答案 0 :(得分:4)

按ID分组。比你能做的更多:

.GroupBy(x => x.Id)
.Select(x => new { x.Key, x.Sum(y => (int?)y.Quantity) });

答案 1 :(得分:0)

如果我假设Id是int而Quantity是字符串,那么你也可以使用聚合。以下是一个例子:

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

按任意键继续。 。

希望它有所帮助。