c# - 将 foreach 循环减少为 linq 查询

标签 c# .net linq

var inventionIds = new List<int>();
List<ProductRemunerationReportingPeriodLink> productRemunerationReportingList = 
        GetAllProductRemunerationReportingPeriodByProductId(productId);

foreach (var rptPeriod in productRemunerationReportingList)
{
    var inventionsList = rptPeriod.Inventions;
    foreach (var link in inventionsList)
    {
                int id  = link.Invention.InventionId;
                inventionIds.Add(id);
    }
}

return inventionIds;

我想最小化两个 for 循环任何人请为此提供一个 nhibernate linq 查询。非常感谢任何帮助。

最佳答案

使用原始变量名称:

var inventionIds =
    productRemunerationReportingList.SelectMany(rptPeriod => rptPeriod.Inventions)
                                    .Select(ProductRemunerationReportingPeriodInvention => ProductRemunerationReportingPeriodInvention.Invention.InventionId)
                                    .ToList();

与更好的命名相同:

var inventionIds = GetAllProductRemunerationReportingPeriodByProductId(productId)
                     .SelectMany(p => p.Inventions)
                     .Select(i => i.Invention.InventionId)
                     .ToList();

提示:变量名的长度应与变量使用的范围相对应。全局可访问的变量应该有漂亮的描述性名称。在短作用域(如 lambda)中使用的变量应该具有非常短的名称。

关于c# - 将 foreach 循环减少为 linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22532563/

相关文章:

.net - 在 Ubuntu 机器上通过 jenkins 发布 .net MVC 解决方案的代码

c# - Linq to Objects - 从数字列表中返回数字对

java - golang为[z][y][x]int定义数组int[x][y][z]有什么好处?

c# - C# 的 Simple-ITK 安装教程

.net - 将 CHM 文件转换为适当的 Intellisense 兼容 XML

c# - XML + LINQ 是否会在 C# 中为大量数据提供良好的性能?

sql - Linq-to-sql 一对多(最大)

c# - nhtmlunit javascript 不工作

c# - Unity多人FPS客户端/服务器交互问题

c# - .Net 列表和最大元素数