如何在行中使用group by?

时间:2017-02-15 16:37:07

标签: c# linq lambda

如何分组以下数据?因为我正在循环整个集合,它只给我一行,因为没有分组到位。 我必须根据Id列对以下记录进行分组,是否有重复的ID?我必须使用那么多行填充模型。

id  name    trID    trName
1   a         5     x
2   b         6     y
2   c         7     z
3   d         8     m
3   e         9     n
4   f         10    0


class DataModel
{

  Public int Id{get;set;}
  Public string name{get;set;}
  Public RepeatedIDs RepeatedIDCollection{get;set;} 

}

class RepeatedIDs 
{
  Public int trId{get;set;}
  Public string trname{get;set;}
}

(from DataRow dr in dataTable.Rows
 select new IdModel
 {
     Id = Convert.ToInt32(dr["ID"]),
     name = Convert.ToString(dr["name"]),

     // need to group the records here and populate below mode with that many rows
     RepeatedIDCollection =  new List<RepeatedIDs>
        {
            new RepeatedIDs()
            {
                trId = Convert.ToInt32(dr["trId"]),
                trname = Convert.ToString(dr["trname"]),
            }
        }
 }).ToList();

2 个答案:

答案 0 :(得分:0)

您需要的是:

var query = dataTable.AsEnumerable()
    .GroupBy(r => r.Field<int>("ID"))
    .Select(grp => new DataModel
    {
        Id = grp.Key,
        name = String.Join(",", grp.Select(t => t.Field<string>("name"))), //Because there could be multiple names
        RepeatedIDCollection = grp.Select(t => new RepeatedIDs
        {
            trId = t.Field<int>("trID"),
            trname = t.Field<string>("trName")
        }).ToList(),
    });

此查询正在做什么:

  • 根据DataTable
  • 中的ID列对数据进行分组
  • 稍后选择DataModel
  • 的对象
  • Id中的DataModel是群组的关键。
  • 分组数据中将有多个名称
  • 稍后通过从分组集合中获取List<RepeatedIDCollection>trId来创建trname

确保在Field方法中指定正确的类型。

答案 1 :(得分:0)

请尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof (int));
            dt.Columns.Add("name", typeof (string));
            dt.Columns.Add("trID", typeof (int));
            dt.Columns.Add("trName", typeof (string));

            dt.Rows.Add(new object[] { 1,"a", 5,"x"});
            dt.Rows.Add(new object[] { 2,"b", 6,"y"});
            dt.Rows.Add(new object[] { 2,"c", 7,"z"});
            dt.Rows.Add(new object[] { 3,"d", 8,"m"});
            dt.Rows.Add(new object[] { 3,"e", 9,"n"});
            dt.Rows.Add(new object[] { 4,"f", 510,"0"});

            var groups = dt.AsEnumerable().GroupBy(x => x.Field<int>("id")).ToList();

        }
    }



}