简体   繁体   中英

LINQ get columns in result by which query was grouped by

I have a problem with getting grouped columns in LINQ.

My class:

public class DTO_CAORAS
{    
    public int? iORAS_KEY_CON { get; set; }
    public int? iMERC_KEY {get;set;}
    public double? decD_ORAS_QUA {get;set;}        
}

LINQ query:

var results =
    from oras in listCAORAS_Delivered
    group oras by new
    {
      oras.iORAS_KEY_CON,
      oras.iMERC_KEY
    }
    into orasGroup
    select new
    {
      decD_ORAS_QUA = orasGroup.Sum(x => x.decD_ORAS_QUA)
    };

List results is filled only with one column - decD_ORAS_QUA . I don't know how to get columns, by which query is grouped - IORAS_KEY_CON and iMERC_KEY ? I would like to fill results with iORAS_KEY_CON, iMERC_KEY and decD_ORAS_QUA.

Input data:

+---------------+-----------+---------------+
| iORAC_KEY_CON | iMERC_Key | decD_ORAS_QUA |
+---------------+-----------+---------------+
|            1  |      888  |             1 |
|            1  |      888  |             2 |
|            1  |      888  |             4 |
+---------------+-----------+---------------+

Desired output:

+---------------+-----------+---------------+
| iORAC_KEY_CON | iMERC_Key | decD_ORAS_QUA |
+---------------+-----------+---------------+
|            1  |      888  |             7 |
+---------------+-----------+---------------+

To also show the keys:

var results = from oras in listCAORAS_Delivered
              group oras by new { oras.iORAS_KEY_CON, oras.iMERC_KEY } into g
              select new DTO_CAORAS {
                  iORAS_KEY_CON = g.Key.iORAS_KEY_CON,
                  iMERC_KEY = g.Key.iMERC_KEY,
                  decD_ORAS_QUA = g.Sum(x => x.decD_ORAS_QUA)
              };

As you are only grouping one column you can also:

var results = from oras in listCAORAS_Delivered
              group oras.decD_ORAS_QUA by new { oras.iORAS_KEY_CON, oras.iMERC_KEY } into g
              select new DTO_CAORAS {
                  iORAS_KEY_CON = g.Key.iORAS_KEY_CON,
                  iMERC_KEY = g.Key.iMERC_KEY,
                  decD_ORAS_QUA = g.Sum()
              };

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