【问题标题】:How to Use Distinct() and Sum() in Single Query in Linq如何在 Linq 的单个查询中使用 Distinct() 和 Sum()
【发布时间】:2015-07-17 16:48:16
【问题描述】:

这里我有 2 列,例如 编号,数量。我想在 LINQ 中获取 Distinct Id 及其数量总和。 我试过这样

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

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

【问题讨论】:

  • 错误信息是什么?
  • 错误 40 'int' 不包含 'Quantity' 的定义,并且找不到接受类型为 'int' 的第一个参数的扩展方法 'Quantity'(您是否缺少 using 指令或装配参考?

标签: linq c#-4.0


【解决方案1】:

按 ID 分组。比你能做的:

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

【讨论】:

  • 我已经重新格式化并进行了更正。GroupBy的结果中没有Value
  • 仍然显示错误
  • @benz 您必须只保留代码的var r = list.Where(some operation) 部分,删除其他所有内容,然后添加此响应中显示的代码。
  • class.Quantity = list.Where(x => x.StatusId == (int)Enum.Attached && x.StatusID != 3).GroupBy(x=>x.JobId).Select (x=>new{x.Key,x.Sum(y=>(int?)y.Quantity)});
  • 为什么要将数量转换为可为空的 int?
【解决方案2】:

如果我假设 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));
        }

    }

结果如下:

1123

2226

3369

4 48

5 5

按任意键继续。 . .

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2012-08-28
    • 2013-03-08
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多