[英]LINQ: get nested arrays based on a groupby?
假設我有這個簡單的對象定義:
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並獲得預期的結果,但這似乎效率低下。
是否有更多的LINQ-ish,或者至少更有效的方式將項目分成組?
你當然可以用.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.