如何在LINQ中获取和使用分组来源?

时间:2018-11-03 05:17:18

标签: c# linq lambda grouping linq-group

我想在分组结果中使用参数“ o”(源对象),如下所示:

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();

但是,我无法在新组中访问“ o”。

1 个答案:

答案 0 :(得分:1)

在group语句中使用分组元素,而不是使用used元素。

   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();

或者,如果要获取任意数量的元素,第一个元素或最后一个元素,则可以使用let关键字。

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();