【问题标题】:DataTable - Linq - select distinct rows based on groupingDataTable - Linq - 根据分组选择不同的行
【发布时间】:2013-08-30 16:56:19
【问题描述】:

这是我的数据表

Type        Product  Action    Quantity
----------  -------  --------  --------
Fruit       Apple    Sales     1
Fruit       Apple    Sales     2
Fruit       Orange   Sales     3
Fruit       Orange   Picking   3
Vegetables  Carrot   Sales     1
Vegetables  Carrot   Sales     3
Vegetables  Carrot   Sales     3
Vegetables  Carrot   Pickings  3

目前我有这个

var tableColumnGrouping =
    from table in ReportConfigurationTable.AsEnumerable()
    group table by new
    {
        column1 = table["Type"],
        column2 = table["Product"]
    }
    into groupedTable
    select new
    {
        tableColumn = groupedTable.Key,  // Each Key contains column1 and column2
        tableColumnCount = groupedTable.Count() 
    };

这会给我以下变量:

{ column1 = "Fruit", column2 = "Apple" }
{ column1 = "Fruit", column2 = "Orange" }
{ column1 = "Vegetable", column2 = "Carrot" }

这是有意的。现在我想从 DataTable 中选择那些不同的值列分组与数据表相遇的地方,然后获取 Action|Quantity 的唯一值。

所以对于 Fruit|Apple 的分组,我将返回两行 Sales|1 Sales|2。

或者,如果有一种非常聪明的方法可以做到这一点而无需进行第二次 foreach,那就太棒了。

如何根据类型|产品的分组从操作|数量列中获取唯一值?

【问题讨论】:

  • 我还不清楚你想要什么,我认为你应该更新详细的示例输出。
  • 这里很简单,所以对于 Fruit|Apple 的分组,我将返回两行 Sales|1 Sales|2
  • 我同意这个问题不清楚。看来您应该使用 Distinct 方法并使用 lambda 语句指定您要应用不同的值,但我不想写答案,因为我不太确定。
  • 所以对于 Fruit|Apple 的分组,我将返回两行 Sales|1 Sales|2

标签: c# linq datatable


【解决方案1】:

当您在 Linq 中使用 Group by 时,您可以将底层项目作为 Enumberable。您需要做的只是另一个 Select 以获得您想要的值

var rptTable = from t in ReportConfigurationTable.AsEnumerable()
                       select new {Type = t["Type"], Product = t["Product"], Action = t["Action"], Quantity = t["Quantity"]};


var tableColumnGrouping = from table in rptTable
                             group table by new { table.Type, table.Product }
                                 into groupedTable
                                 select new
                                 {
                                     tableColumn = groupedTable.Key,
                                     tableColumnCount = groupedTable.Count(),
                                     actions = groupedTable.Select(t => new {Action = t.Action, Quantity = t.Quantity})
                                 };

【讨论】:

  • Jeremy - 感谢您的尝试,但我认为您提供的线路可能有问题。
  • 方法'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)'的类型参数不能从用法推断。尝试明确指定类型参数
  • .Net 无法弄清楚 ReportConfigurationTable 包含的内容。尝试先选择匿名(如果不起作用,则选择具体类型),然后进行分组等。代码已更新
猜你喜欢
  • 2017-01-10
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多