简体   繁体   中英

DataTable - Linq - select distinct rows based on grouping

Here is my datatable

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

currently I have this

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() 
    };

This will give me there vars of:

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

Which is intended. Now I want to select from the DataTable where those distinct values column grouping meets the datatable and then get the unique values for Action|Quantity.

So for the grouping of Fruit|Apple, I would return the two rows of Sales|1 Sales|2.

Or if there is a really clever way of doing this without doing a second foreach, that would be fantastic.

How do I get the unique values from the columns Action|Quantity based on the grouping on Type|Product?

When you use Group by in Linq you can get to the underlying items as an Enumberable. All you need to do is another Select to get just the values you want

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})
                                 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM