How to get and use source of grouping in LINQ?

Viewed 139

I'd like to use parameter "o" (the source object) in the result of grouping, as so:

return (from o in objects
        group o by MySpecialConverter(o) into g
        select new Group
        {
            Key = g.Key,    
            Items = g.ToList(),         
            Source = o, // Error: The name 'o' does not exist in the current context.
            ...
        }).ToList();

However, I am not able to access "o" in the new group.

1 Answers

Use the grouped element rather than using the used element in group statement.

   return (from o in objects
            group o by MySpecialConverter(o) into g
            select new Group // Create Group class with the data types and  object bellow 
            {
                Key = g.Key,    
                Items = g.ToList(),         
                Source = g // used the grouped element here for selection 
            }).ToList();

Or if you want to get any number of element or first element or last element you can use the let key word.

return (from o in objects
                group o by MySpecialConverter(o) into g
                let oLocal = g.FirstOrDefault() 
                select new Group // Create Group class with the data types and  object bellow 
                {
                    Key = g.Key,    
                    Items = g.ToList(),         
                    Source = oLocal // used the grouped element here for selection 
                }).ToList();
Related