0

I'm running into a bit of a problem writing a LINQ Query.

Given this data

Object ID Items ------ -- ----- Object1 1 [1,2,4] Object2 2 [2] Object3 3 [2,4] Object4 4 [1] 

I want to group on the IDS inside my Items property

The end result should be something like this

ItemID Objects ------ ------------------------------------ 1 [Object1, Object2, Object3, Object4] 2 [Object1, Object2, Object3] 4 [Object1, Object3] 

In which "Objects" contains the entire "object", or the properties that I wish to select.

Any help with this? It's probably pretty basic, but I can't wrap my head around it right now.

2
  • 1
    Can you explain the logic how to transform the first table to the second? Commented Sep 22, 2013 at 21:40
  • how do you know which ItemIDs to look for? is it always from 1 to (known) n? union of all Items lists? Commented Sep 22, 2013 at 21:41

2 Answers 2

1

Try following pseudocode

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked. Late accept because I was cursing at the code until I finally noticed I erroneously put a wrong bracket somewhere.
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() } 

1 Comment

Glancing over the code, I assume it does the same as Tilak's code. I accepted his answer because I prefer LINQ method syntax over query syntax.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.