是否可以将以下代码转换为Linq,它看起来会更好一些
foreach (var entry in bottleneck.Item2)
{
if(entry.ChangeoverTime > 0)
{
avarangechangeOverTimes += entry.ChangeoverTime;
++counter;
}
if (entry.ChangeoverTime > maxchangeOverTimes)
{
maxchangeOverTimes = entry.ChangeoverTime;
}
changeovertime.ChangeoverTimes.Add
(
new ChangeOverDateValue
{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}
);
}
答案 0 :(得分:3)
如果bottleneck.Item2
中的条目数量不是很大,您可以使用这三个语句实现相同的目标:
var maxChangeOverTime = bottleneck.Item2.Max(x => x.ChangeoverTime);
var averageChangeOverTime = bottleneck.Item2.Average(x => x.ChangeoverTime);
var result
= bottleneck.Item2
.Select(x => new ChangeOverDateValue
{
ChangeoverValue = x.ChangeoverTime,
Color = ChangeOverTimeToColor(x.ChangeoverTime),
StartTime = x.StartTime
});
changeovertime.ChangeoverTimes.AddRange(result);
请注意,这将枚举bottleneck.Item2
三次而不是一次使用您当前的代码。
答案 1 :(得分:0)
我认为你只能改变外部的foreach:
bottleneck.Items2.ToList().Foreach(entry =>
{
// your code
});
答案 2 :(得分:0)
bottleneck.Item2.where(entry => entry.ChangeoverTime).ToList().Foreach(entry => {
avarangechangeOverTimes += entry.ChangeoverTime;
++counter;
});
maxchangeOverTimes = bottleneck.Item2.max=(entry => entry.ChangeoverTime);
changeovertime.ChangeoverTimes.AddAll(bottleneck.Item2.select(entry => new new ChangeOverDateValue
{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}));
这是我能想到的所有内容,而没有更多的信息或我的发展环境
答案 3 :(得分:0)
也许......
var avarangechangeOverTimes = bottleneck.Item2
.Where(entry => entry.ChangeOverTime > 0)
.Sum(entry => entry.ChangeOverTime);
var maxchangeOverTimes = bottleneck.Item2
.Max(entry => entry.ChangeOverTime);
bottleneck.Item2.ToList()
.ForEach(entry => changeovertime.ChangeoverTimes.Add
(
new ChangeOverDateValue {
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}
)
);
答案 4 :(得分:0)
试试这个:
var averagechangeOverTimes = bottleneck.Item2
.Where(entry => entry.ChangeoverTime > 0)
.Sum(entry => entry.ChangeoverTime);
counter = bottleneck.Item2.Count(entry => entry.ChangeoverTime > 0);
var maxchangeOverTimes = bottleneck.Item2.Max(entry => entry.ChangeoverTimes);
changeovertime.ChangeoverTime.Add(bottleneck.Item2
.Select(entry => new ChangeOverDateValue{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
});