After grouping by, can I refer to the elements of the original IEnumerable in a LINQ query?

Posted by michielvoo on Stack Overflow See other posts from Stack Overflow or by michielvoo
Published on 2010-05-12T10:14:04Z Indexed on 2010/05/13 20:34 UTC
Read the original article Hit count: 197

Filed under:
|

Example:

from OriginalObject in ListOfOriginalObjects

group new CustomObject {
  X = OriginalObject.A, 
  Y = OriginalObject.B
} by OriginalObject.Z into grouping 

select new GroupOfCustomObjects {
  Z = grouping.Key, 
  C = OriginalObject.C, 
  group = grouping
}

In the select part of the query, I'd like to add a property (OriginalObject.C) to the type GroupOfCustomObjects. But it seems that OriginalObject is out of scope in that part of the query. I can sort of understand why, since I am not grouping on that property and I am also not making that property part of CustomObject that I'm grouping.

One workaround is to add a property C to CustomObject and the in the GroupOfCustomObjects read the value of the first CustomObject in the grouping. My issue with that is that I'm adding a property to an object that doesn't need it (CustomObject), just to be able to add it to the GroupOfCustomObjects.

I hope I have explained this properly!

Is there a way to refer to the OriginalObject that the query starts with?

Thanks!

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about group-by