Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ:基于groupby获取嵌套数组?_C#_Linq_Nested - Fatal编程技术网

C# LINQ:基于groupby获取嵌套数组?

C# LINQ:基于groupby获取嵌套数组?,c#,linq,nested,C#,Linq,Nested,假设我有一个简单的对象定义: public class Item { public int section { get; set; } public string item { get; set; } } 我在一个深度数组中有一些数据。这是JSON,将通过JSON.NET转换为C对象: [ { "section": 0, "item": "Hello!" }, { "section": 1, "item": "First Steps

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

public class Item
{
    public int section { get; set; }
    public string item { get; set; }
}
我在一个深度数组中有一些数据。这是JSON,将通过JSON.NET转换为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并获得预期的结果,但这似乎效率低下


是否有一种更简单,或者至少更有效的方法将项目分成组?

您当然可以使用.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