c# - 将嵌套 Foreach 转换为 Linq

标签 c# linq

我正在尝试使用 LINQ 重写以下内容

foreach (WMCommon.Services.StakeOut.assembly ass in assemblies) 
{
  foreach (var agg in aggregate) 
  {
    if ( agg.catagory.unitActn   == ass.unitActn   &&
         agg.catagory.unitCode   == ass.unitCode   &&
         agg.catagory.unitLength == ass.unitLength
    ) 
    {
      ass.quantity = agg.qty;
    }
  }
}

这是我得到的:

assemblies.Where( a => a.quantity = ( aggregate.Where( p => p.catagory.unitActn == a.unitActn && p.catagory.unitCode == a.unitCode && p.catagory.unitLength == a.unitLength).Select(s=>s.qty)));

提前感谢您的帮助。我希望 LINQ 比嵌套的 FOREACH 快得多吗?

最佳答案

I am hoping that the LINQ will be much faster than nested FOREACH?

一般而言,LINQ 不会提高您的性能,除非您更改它的工作方式。 LINQ 实际上只是为您执行迭代。

在这种情况下,您似乎可以只使用连接来改善整体效果,因为这会给您带来相同的效果:

var query = from WMCommon.Services.StakeOut.assembly ass in assemblies
            join agg in aggregate
            on new { ass.unitActn, ass.unitCode, ass.unitLength } equals new { (agg.catagory.unitActn, agg.catagory.unitCode, agg.catagory.unitLength }
            select new { ass, agg };

foreach(var pair in query)
    pair.ass.quantity = pair.agg.qty;

关于c# - 将嵌套 Foreach 转换为 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340405/

相关文章:

c# - C# 中的枚举

c# - Windows 窗体文本框 : Selection and Caret position

c# - 如何比较多个文本框并在它们不相等时触发验证器 C#

c# - 在 C# 中显示分层数据

c# - 在 azure 上发布时列名无效

sql - 适合 MS SQL Server 的表编辑器好用吗?

c# - 如何在 Windows 和 IANA 时区之间进行转换?

c# - 在 x 个较小列表之间平均拆分项目列表

linq - Entity Framework 似乎不必要地两次加入同一个表

c# - 获取每个项目的最大值通用列表