简体   繁体   中英

Linq syntax c# to select two field from table

i am writing the following linq code in c#

      var groupedData = from b in dt.AsEnumerable()
                      group b by b.Field<string>("TypeColor") into g

                      select new
                      {

                          Key = g.Key,

                          Value = g.Select(r => r.Field<int>("Price")),
                          Price = g.Select(r => r.Field<int>("Price"))

                      };

 foreach (var g in groupedData)
    {
        string s = g.Key;
}

how can i select two or more field from the datatable and group the table with one field. Can any body help me? Here dt is a datatable which is binding from database

You need to aggregate the fields if you've grouped the rows(similar as in SQL):

var groupedData = from b in dt.AsEnumerable()
                  group b by b.Field<string>("TypeColor") into g
                  select new
                  {
                      Color = g.Key,
                      PriceSum = g.Sum(r => r.Field<int>("Price")),
                      FirstValue = g.First().Field<int>("Value")
                  };

foreach (var g in groupedData)
{
    string color = g.Color;
    Double priceSum = g.PriceSum;
    int firstValue = g.FirstValue;
} 

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