LINQ:获取基于groupby的嵌套数组

本文关键字:嵌套 数组 groupby 获取 LINQ | 更新日期: 2023-09-27 18:06:57

假设我有这个简单的对象定义:

public class Item
{
    public int section { get; set; }
    public string item { get; set; }
}

我有一些数据在单深度数组。这是JSON,它将通过JSON转换为c#对象。净:

[
  {
    "section": 0,
    "item": "Hello!"
  },
  { 
    "section": 1,
    "item": "First Steps"
  },
  {
    "section": 1,
    "item": "How to Ask for Help"
  },
  {
    "section": 2,
    "item": "Your First Program"
  },
  {
    "section": 2,
    "item": "The Code"
  },
  {
    "section": 2,
    "item": "How It Works"
  },
  {
    "section": 3,
    "item": "Where To Go From Here"
  }
]

使用实体框架或其他方法,我已经得到了上述这些对象的简单列表,包含在var变量中。

现在我想做的是获得相同的列表,但是每个部分都被分组为外部数组中的数组。例如,我想要的JSON看起来像这样:

[
  [
    {
      "section": 0,
      "item": "Hello!"
    }
  ],
  [
    { 
      "section": 1,
      "item": "First Steps"
    },
    {
      "section": 1,
      "item": "How to Ask for Help"
    }
  ],
  [
    {
      "section": 2,
      "item": "Your First Program"
    },
    {
      "section": 2,
      "item": "The Code"
    },
    {
      "section": 2,
      "item": "How It Works"
    }
  ],
  [
    {
      "section": 3,
      "item": "Where To Go From Here"
    }
  ]
]

我最初的想法是用groupby语句做LINQ查询,但我不认为这是我要找的- groupby似乎类似于SQL版本,所以它只能用于聚合操作。

到目前为止,我发现的唯一其他选择是使用LINQ查询来获取所有节的列表:

var allSections = (from x in myData select x.section).Distinct();

…然后遍历这些id并手动构建数组:

List<List<Item>> mainList = new List<List<Item>>();
foreach (int thisSection in allSections.ToArray()) 
{
    List<Item> thisSectionsItems = (from x in myData where x.section == thisSection select x).ToList();
    mainList.Add(thisSectionsItems);
}
return mainList;

这应该会产生一个适当的可枚举对象,我可以将其输入JSON。NET并得到预期的结果,但这似乎效率低下。

是否有一种更接近linq,或者至少更有效的方法来将项目分成组?

LINQ:获取基于groupby的嵌套数组

您当然可以使用.GroupBy()实现这一点

var grouped = items
    .GroupBy(x => x.section)    // group by section
    .Select(x => x.ToArray())   // build the inner arrays
    .ToArray();                 // return collection of arrays as an array