开发者

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

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!


The into clause wipes clean the scope. OriginalObject is removed from scope at that point.

Try it this way:

from OriginalObject in ListOfOriginalObjects 
group OriginalObject by OriginalObject.Z into grouping  
select new GroupOfCustomObjects { 
  Z = grouping.Key,  
  C = grouping.First().C,  
  group = grouping.Select(x => 
    new CustomObject { 
      X = x.A,  
      Y = x.B 
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜