按List对象分组

时间:2016-10-21 20:16:08

标签: c# asp.net linq

您好我正在尝试使用LINQ对我收到的一些数据进行分组。数据:

[
  {
    "TicketID": 11,
    "Priority": 1,
    "Email": "someemail@asdf.com",        
    "Files": [
      {
        "FileID": 1,
        "FileName": "file1.png"
      }
    ]
  },
  {
    "TicketID": 11,
    "Priority": 1,
    "Email": "someemail@asdf.com",        
    "Files": [
      {
        "FileID": 2,
        "FileName": "file2.png"
      }
    ]
  },
  {
    "TicketID": 11,
    "Priority": 1,
    "Email": "someemail@asdf.com",        
    "Files": [
      {
        "FileID": 3,
        "FileName": "file3.png"
      }
    ]
  },
]

是否可以这样分组:

[
  {
    "TicketID": 11,
    "Priority": 1,
    "Email": "someemail@asdf.com",        
    "Files": [
      {
        "FileID": 1,
        "FileName": "file1.png"
      },
      {
        "FileID": 2,
        "FileName": "file2.png"
      },
      {
        "FileID": 3,
        "FileName": "file3.png"
      }
    ]
  }
]

我尝试使用LINQ:

var newList = list.GroupBy(gb => gb.TicketID).SelectMany(s => s);

但它的输出与原始输出相同。也许有人会知道。 谢谢!

2 个答案:

答案 0 :(得分:1)

假设TicketIDEmailPriority是您想要将数组组合在一起的键,那么您可以这样做:

var groupedList = list.GroupBy(i => new
{
    i.TicketID,
    i.Priority,
    i.Email
}).Select(g => new Ticket()
{
    TicketID = g.Key.TicketID,
    Email = g.Key.Email,
    Priority = g.Key.Priority,
    Files = g.SelectMany(x => x.Files).ToList()
}).ToList();

其中Ticket是表示示例中JSON的类。

答案 1 :(得分:0)

如果您只有一个TicketID,那么您可以这样做(调用您的数据src):

var tf = src.First();
var ans = new { TicketID = tf.TicketID, Priority = tf.Priority, Email = tf.Email,
    Files = src.SelectMany(t => t.Files).ToArray() };

如果你想在你的答案中处理多个TicketID并按TicketID组合它们,那么就像这样:

var ans = src.GroupBy(t => t.TicketID).Select(
    gp => new { GP = gp, GPF = gp.First() }).Select(
        gpf => new { TickedID=gpf.GPF.TicketID, Priority = gpf.GPF.Priority,
                     Email = gpf.GPF.Email,
                     Files = gpf.GP.SelectMany(gp => gp.Files).ToArray() }).ToArray();

第一个Select只是为了模拟一个Let来防止重复字段重复gp.First()。查询语法如下:

var ans = from t in src 
          group t by t.TicketID into gp
          let gpf = gp.First()
          select new { TicketID = gpf.TicketID, Priority = gpf.Priority, Email = gpf.Email,
                       Files = gp.SelectMany(gp => gp.Files).ToArray() };