gpt4 book ai didi

c# - 重构这个 Lambda 表达式

转载 作者:行者123 更新时间:2023-11-30 13:39:16 25 4
gpt4 key购买 nike

我需要重构此代码,以便数据服务不会为每个行项目查询两个 workType。提前致谢。

        _attributeGroups = attributeGroups.Select(attributeGroupRowModel =>
new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = workTypes.First(wt => wt.Id == attributeGroupRowModel.WorkTypeId).Description,
IsExpired = workTypes.First(wt => wt.Id == attributeGroupRowModel.WorkTypeId).IsExpired, //todo: not efficient, to be refactored
}).ToList();

最佳答案

_attributeGroups = attributeGroups.Select(attributeGroupRowModel => 
{
var wt = workTypes.First(x => x.Id == attributeGroupRowModel.WorkTypeId);
return new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = wt.Description,
IsExpired = wt.IsExpired,
};
}).ToList();

或者如果您更喜欢 LINQ:

_attributeGroups = 
(from attributeGroupRowModel in attributeGroups
let wt = workTypes.First(x => x.Id == attributeGroupRowModel.WorkTypeId)
select new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = wt.Description,
IsExpired = wt.IsExpired,
}).ToList();

关于c# - 重构这个 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com