3

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
g_m
  • 456
  • 1
  • 3
  • 12
  • You've grouped your data, so `o` no longer means anything. What were you hoping to put into `Source` (that isn't already held in `Items`)? – John Wu Nov 03 '18 at 05:25
  • thank you for the comment, I completed the post with the error message "The name 'o' does not exist in the current context" – g_m Nov 03 '18 at 05:25
  • @JohnWu Presumably "o" would be 'all the times', thus being in *addition to* the 'items for this group'.. – user2864740 Nov 03 '18 at 05:28
  • Yes, @JohnWu, you are absolutelly right. "o" means nothing and there is not one instance of "o" after grouping. Sorry for the confusion – g_m Nov 03 '18 at 05:31
  • @g_m in that case is there still a question? :) – Gilad Green Nov 03 '18 at 05:32
  • I have no more questions. My concept of using "o" in this place was unfounded. Thank you for your support. I'm sorry, my mistake in thinking :( – g_m Nov 03 '18 at 05:37
  • use this Source = g then you find your desired elements here – Muhammad Ashikuzzaman Nov 03 '18 at 06:08

1 Answers1

1

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();
Muhammad Ashikuzzaman
  • 3,075
  • 6
  • 29
  • 53
  • The second option is great, thank you! I thought there was no answer, but it turns out that you found it. I like it because that's what I needed in my solution. – g_m Nov 03 '18 at 09:32