我们有以下定义 LINQ:myList.Select(s=> new DtoTest(){ TotalSamples = myList.Count(c=> c.UserId == s.UserId), EvaluatedSamples = myList.Count(c=> c.UserId == s.UserId && c.Status == Status.OK) PercentageRealized = (myList.Count(c=> c.UserId == s.UserId) / myList.Count(c=> c.UserId == s.UserId && c.Status == Status.OK)) * 100});有没有一种方法可以分配属性值“PercentageRealized”,而无需使用以前在“TotalSamples”和“EvaluatedSamples”中使用的相同函数?像这样的东西:myList.Select(s=> new DtoTest(){ TotalSamples = myList.Count(c=> c.UserId == s.UserId), EvaluatedSamples = myList.Count(c=> c.UserId == s.UserId && c.Status == Status.OK) PercentageRealized = (TotalSamples / EvaluatedSamples) * 100 //<-!Not possible!});还有其他提示吗?
3 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
更改函数委托以使用已计算的值
myList.Select(s => {
var result = new DtoTest() {
TotalSamples = myList.Count(c => c.UserId == s.UserId),
EvaluatedSamples = myList.Count(c => c.UserId == s.UserId && c.Status == Status.OK)
};
result.PercentageRealized = (result.TotalSamples / result.EvaluatedSamples) * 100;
return result;
});
慕勒3428872
TA贡献1848条经验 获得超6个赞
如果您使用的是匿名类型,这会更复杂,但由于DtoTest是一个类,您总是可以将您的数学移动到属性中。
public class DtoTest
{
public float PercentageRealized
{
get { return (TotalSamples / EvaluatedSamples) * 100; }
}
}
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
如果PercentageRealized
是那么简单的计算,为什么不在类中的属性中进行计算,在类 DTOTest 中是这样的:
public float PercentageRealized => (TotalSamples / EvaluatedSamples) * 100;
- 3 回答
- 0 关注
- 197 浏览
添加回答
举报
0/150
提交
取消