我在编写LINQ查询时遇到了一些问题。
鉴于此数据
Object ID Items
------ -- -----
Object1 1 [1,2,4]
Object2 2 [2]
Object3 3 [2,4]
Object4 4 [1]
我想在Items
属性
最终结果应该是这样的
ItemID Objects
------ ------------------------------------
1 [Object1, Object2, Object3, Object4]
2 [Object1, Object2, Object3]
4 [Object1, Object3]
其中“Objects”包含整个“对象”或我想要选择的属性。
对此有何帮助? 它可能非常基本,但我现在无法绕过它。
答案 0 :(得分:1)
尝试以下伪代码
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
答案 1 :(得分:1)
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() }