将foreach循环减少为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;

我想尽量减少两个循环任何人请为此提供一个非hibernate的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,应该有非常短的名称。

List<int> inventionIds = (from rptPeriod in productRemunerationReportingList 
from ProductRemunerationReportingPeriodInvention in rptPeriod.Inventions
select ProductRemunerationReportingPeriodInvention.Invention.InventionId).ToList<int>();

相关内容

  • 没有找到相关文章

最新更新