は、私はこの単純なオブジェクト定義があるとします。LINQ:groupbyに基づいてネストされた配列を取得しますか?
public class Item
{
public int section { get; set; }
public string item { get; set; }
}
私は、単一の深さの配列のいくつかのデータを持っています。これはJson.NETを経由してC#のオブジェクトに変換されるだろう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"
}
]
は、私は、これらのオブジェクトの単純なリストに到着した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、または少なくともより効率的なアイテムをグループに分割する方法はありますか?
でこれを達成することができます。ありがとう。 – fdmillion