猿问

使用 LINQ 从类属性中计算百分比的更好方法

我们有以下定义 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!

});

还有其他提示吗?


波斯汪
浏览 198回答 3
3回答

呼唤远方

更改函数委托以使用已计算的值myList.Select(s => {&nbsp; &nbsp; var result = new DtoTest() {&nbsp; &nbsp; &nbsp; &nbsp; TotalSamples = myList.Count(c => c.UserId == s.UserId),&nbsp; &nbsp; &nbsp; &nbsp; EvaluatedSamples = myList.Count(c => c.UserId == s.UserId && c.Status == Status.OK)&nbsp; &nbsp; };&nbsp; &nbsp; result.PercentageRealized = (result.TotalSamples / result.EvaluatedSamples) * 100;&nbsp; &nbsp; return result;});

慕勒3428872

如果您使用的是匿名类型,这会更复杂,但由于DtoTest是一个类,您总是可以将您的数学移动到属性中。public class DtoTest{&nbsp; &nbsp; public float PercentageRealized&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return (TotalSamples / EvaluatedSamples) * 100; }&nbsp; &nbsp; }}

慕盖茨4494581

如果PercentageRealized&nbsp;是那么简单的计算,为什么不在类中的属性中进行计算,在类 DTOTest 中是这样的:public&nbsp;float&nbsp;PercentageRealized&nbsp;=>&nbsp;(TotalSamples&nbsp;/&nbsp;EvaluatedSamples)&nbsp;*&nbsp;100;
随时随地看视频慕课网APP
我要回答