You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将LINQ查询与foreach逻辑合并以优化C#代码性能?

C#代码优化:将foreach逻辑合并到LINQ查询中

原代码

var ApprovedAllowancesProductIds = from item in ApprovedAllowancesListFiltered select item.ProductId; //(1)

List<Product> productList = new List<Product>();
List<string> partitionProductKeys = new List<string>();

foreach (var item in ApprovedAllowancesProductIds)   //(2)
{
    string[] partitionKey = new string[] { CountryCD, item.ToString() };
    string PartitionKey = partitionKey.ConcatenatedStringWithPipeSeparator();
    partitionProductKeys.Add(PartitionKey);
}

var resultProduct = await _tableStorageService.FetchDataByMultiplePartitionKey<Product>(partitionProductKeys, QueryComparisonEnums.Equal);
productList.Add((Product)resultProduct);

需求

我需要优化这段代码,把标记为(2)的foreach循环功能直接合并到标记为(1)的LINQ查询中,以此提升性能。我曾参考过StackOverflow上的两个相关示例,但它们不符合我的具体需求,请勿将此问题标记为重复。

优化后的代码

可以直接通过LINQ的Select链式调用完成分区键的生成,无需单独的foreach循环:

// 合并原(1)和(2)的逻辑,直接生成分区键列表
var partitionProductKeys = ApprovedAllowancesListFiltered
    .Select(item => new[] { CountryCD, item.ProductId.ToString() }
        .ConcatenatedStringWithPipeSeparator())
    .ToList();

List<Product> productList = new List<Product>();
var resultProduct = await _tableStorageService.FetchDataByMultiplePartitionKey<Product>(partitionProductKeys, QueryComparisonEnums.Equal);
productList.Add((Product)resultProduct);

如果需要保留ApprovedAllowancesProductIds变量,也可以拆分两步:

// 原(1)的LINQ查询
var ApprovedAllowancesProductIds = ApprovedAllowancesListFiltered.Select(item => item.ProductId);
// 合并原(2)的foreach逻辑到LINQ中
var partitionProductKeys = ApprovedAllowancesProductIds
    .Select(id => new[] { CountryCD, id.ToString() }
        .ConcatenatedStringWithPipeSeparator())
    .ToList();

List<Product> productList = new List<Product>();
var resultProduct = await _tableStorageService.FetchDataByMultiplePartitionKey<Product>(partitionProductKeys, QueryComparisonEnums.Equal);
productList.Add((Product)resultProduct);

说明

优化后的代码通过LINQ链式调用替代了显式foreach循环,避免手动维护列表添加操作,代码更简洁紧凑。性能上和原foreach相当,但可读性和可维护性更好,同时满足将foreach逻辑合并到LINQ查询的需求。

内容的提问来源于stack exchange,提问作者Abhishek_Singh_Rana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:35:34