如何对从SQL Server接收的数据进行分组

时间:2017-07-20 11:20:42

标签: c# linq

这是我从SQLServer接收的数据

+--------+--------------+
| Role   | DocumentType |
+--------+--------------+
| Admin  | Z24          |
| Admin  | Z25          |
| User   | Z24          |
| User   | Z25          |
| DocUser| Z26          |
| Admin  | Z26          |
| User   | Z26          |
| Admin  | Z27          |
+--------+--------------+

我想使用C#

将上述数据存储在下面的列表中
Admin - Z24, Z25, Z26, Z27
User - Z24,Z25, Z26
DocUser - Z26

有人可以帮助我吗?

这是一个类似的例子

class Document
{
    public string DocType { get; set; }
    public string DocName { get; set; }
    public int Value { get; set; }
}
class Program
{
   static void Main(string[] args)
   {
      var docs = new List<Document>();
      docs.Add(new Document { DocType = "Main", DocName = "A", Value = 1 });
      docs.Add(new Document { DocType = "Main", DocName = "B", Value = 2 });
      docs.Add(new Document { DocType = "Main", DocName = "C", Value = 3 });
      docs.Add(new Document { DocType = "Main", DocName = "D", Value = 4 });
      docs.Add(new Document { DocType = "Main1", DocName = "D", Value = 4 });
      docs.Add(new Document { DocType = "Main1", DocName = "D", Value = 4 });
      var groupedData = docs.GroupBy(d => d.DocType).Select(group => group.ToList()).ToList();
   }
}

1 个答案:

答案 0 :(得分:0)

如果您只想检索部分列,请使用以下重载:

var result = data.GroupBy(key => key.Role, element => element.DocumentType);

否则您也可以使用此投影:

var result = data.GroupBy(key => key.Role)
                 .Select(g => new {
                     Role = g.Key,
                     Documents = g.Select(i => i.DocumentType)
                 });