[英]LINQ Group-by clause on Enumerable field
我在編寫LINQ查詢時遇到了一些問題。
鑒於此數據
Object ID Items
------ -- -----
Object1 1 [1,2,4]
Object2 2 [2]
Object3 3 [2,4]
Object4 4 [1]
我想在Items
屬性中對IDS進行分組
最終結果應該是這樣的
ItemID Objects
------ ------------------------------------
1 [Object1, Object2, Object3, Object4]
2 [Object1, Object2, Object3]
4 [Object1, Object3]
其中“對象”包含整個“對象”,或者我想要選擇的屬性。
對此有何幫助? 它可能非常基本,但我現在無法繞過它。
嘗試以下偽代碼
var result = objects.SelectMany ( o=>o.Items.Select (x=>new {item=x,objectid=o.object)).GroupBy (x=>x.item).ToArray()
// objects -> collection of objects in question
//Items.Select => create list of item to object mapping
//objects.SelectMany -> Flattens item to object mapping into IEnumerable
//.GroupBy => groups the result by itemid
var results = from o in source
from i in o.Items
group o.Object by i into g
select new { ItemId = g.Key, Objects = g.ToList() }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.