【问题标题】:Aggregating DataTable Without LINQ在没有 LINQ 的情况下聚合 DataTable
【发布时间】:2017-07-05 11:17:05
【问题描述】:

我想根据一些不同的值聚合数据表行。我必须使用 Select 和 Compute 方法或其他非 linq 方法。 我的问题是:我如何聚合(sum、count、min 和 ...)和分组字段,并像 sql server 表一样获得结果。考虑一下我有一个包含四列 a、b、c、d 的表。当我想基于 'b' 聚合 'a' 时,我可以这样写:

Select sum(a) as 'a', b
from myTable
group by b

而 sql 服务器创建了一个包含两列“a”和“b”的表,那么我如何在 C# 中使用 DataTables 来执行此操作? 我在 MSDN 和其他相关来源中看到了 DataTable.Compute() 的示例,用于在数据表中聚合和分组数据,但它只返回一个对象值,并且对于分组数据表中的行没有用。在我的问题中,用户喜欢在运行时使用summinmax 或...,我试图找到创建一些动态查询的解决方案。

【问题讨论】:

  • 您为什么想使用 LINQ?
  • Sum、Min、Max、Count、Avg 的使用是动态的,用户决定如何聚合字段。在 LINQ 中你没有动态查询(以一种简单的方式!)
  • weblogs.asp.net/scottgu/…nlinq.codeplex.com 是否适合您的需求?
  • @mjwills,非常感谢 weblogs.asp.net/scottgu/...!这很棒。我以前见过,但不是那么仔细!其实你救了我的一天!

标签: c# sql-server linq datatable


【解决方案1】:

您应该使用Dynamic LINQ。它允许您根据字符串输入执行 LINQ。

【讨论】:

【解决方案2】:

尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication64
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("a", typeof(int));
            dt.Columns.Add("b", typeof(string));
            dt.Columns.Add("c", typeof(string));
            dt.Columns.Add("d", typeof(string));

            dt.Rows.Add(new object[] { 1, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 2, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 3, "b1", "c", "d" });
            dt.Rows.Add(new object[] { 4, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 5, "b2", "c", "d" });
            dt.Rows.Add(new object[] { 6, "b3", "c", "d" });
            dt.Rows.Add(new object[] { 7, "b4", "c", "d" });


            var results = dt.AsEnumerable().GroupBy(x => x.Field<string>("b")).Select(x => new { key = x.Key, sum = x.Sum(y => y.Field<int>("a"))}).ToList();
        }
    }
}

【讨论】:

  • 这使用 LINQ。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多