c# - 如何在 LINQ 中获取和使用分组源?

标签 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”。

最佳答案

使用分组的元素而不是在组语句中使用已使用的元素。

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

关于c# - 如何在 LINQ 中获取和使用分组源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53128616/

相关文章:

c# - 在 MongoDB C# 驱动程序 2.2 中使用 AsQueryable 进行投影

C# - 从 SQL 到 Linq - 左外连接/内连接

lambda - 组合对特定类型的任意对象的实例方法的引用

java - 使用 Lambda 表达式计算名字的数量

linq - 帮助转换为linq

vb.net - Lambda 表达式创建多个查询

c# - 在多线程 Windows 服务应用程序中使用的最佳 NHibernate session 管理方法是什么?

c# - 将窗口按钮置于前面

c# - 在 MVVM 模式中单击时更改按钮颜色

sql-server - 始终加密、LINQ 以及包含位置