gpt4 book ai didi

C# LINQ 表达式变得相当长

转载 作者:行者123 更新时间:2023-12-04 04:08:34 25 4
gpt4 key购买 nike

所以,我的代码中有一个对象(容器)列表,我想检查我要添加的容器是否会影响每个容器顶部的最大重量(container.MaxWeightOnTop).我创建了这个函数:

    private bool TooMuchWeight(Container referenceContainer)
{
var tempList = _containers;
tempList.Add(referenceContainer);
SortStack(tempList);

foreach (var container in tempList)
{
var index = tempList.FindIndex(c => c == container);
var weightOnContainer = tempList.Where(c => tempList.FindIndex(i => i == container) > index)
.Sum(c => container.Weight);

if (weightOnContainer > Container.MaxWeightOnTop)
return false;
}

return true;
}

如您所见,它变得相当长,我的 IDE 甚至建议将此 LINQ 表达式用于整个 foreach 循环:

 return (from container in tempList
let index = tempList.FindIndex(c => c == container)
select tempList.Where(c => tempList.FindIndex(i => i == container) > index)
.Sum(c => container.Weight)).All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);

即使我使用 .GetRange 函数,它仍然很长:

return tempList
.Select(container =>
tempList.GetRange(tempList.FindIndex(c => c == container), Length).Sum(c => c.Weight))
.All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);

问题:是否可以压缩这个表达式?

最佳答案

就可读性和性能而言,我认为您的代码可以利用索引 Enumerable.Select重载和值元组:

    var tempList = _containers;
tempList.Add(referenceContainer);
SortStack(tempList);
var indexed = tempList.Select((container, index) => (container, index)).ToList();
foreach (var (container, index) in indexed)
{
var weightOnContainer = indexed
.Where((c, i) => i > index)
.Sum((c, i) => c.Weight);

if (weightOnContainer > Container.MaxWeightOnTop)
return false;
}

同样在原始版本中 .Sum(c => container.Weight) 子句对我来说看起来有点古怪,不应该是 .Sum(c => c.Weight)

关于C# LINQ 表达式变得相当长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62131279/

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