简体   繁体   English

Linq匿名类型

[英]Linq Anonymous Type

I don't often use LINQ and the thing about it is that there are efficient ways of using it an less efficient ways. 我不经常使用LINQ,关于它的事情是有一些有效的方法来使用它,而不是效率较低的方法。

I have a list of items, and I simply want to do a calculation on each and return the lowest calculated decimal number (note number, not item). 我有一个项目列表,我只想对每个项目进行计算并返回计算出的最低十进制数字(音符编号,而不是项目)。 I have this LINQ which works but I wonder if it is the most efficient way LINQ can be used in this scenario. 我有这个LINQ可以工作,但是我想知道这是否是在这种情况下使用LINQ的最有效方法。

var bestPrice = query.Select(x => new
{
    Interest = CalcInterest(amount, term, x.ProductRate.Rate)
})
.OrderBy(x => x.Interest)
.FirstOrDefault();

Where "query" is a preselected LINQ list, and "CalcInterest" is a method used to calculate the number. 其中“查询”是预选的LINQ列表,而“ CalcInterest”是用于计算数字的方法。

This query will be used a lot, so any small gains will be big wins. 该查询将被大量使用,因此任何小的收获都是大赢家。

You don't need anonymous types here, I think. 我认为您在这里不需要匿名类型。 Try this: 尝试这个:

var bestPrice = query.Min(x => CalcInterest(amount, term, x.ProductRate.Rate));

Edit: playing around with it I realized this created a different result. 编辑:玩弄它,我意识到这创造了不同的结果。 Your code returns an anon type. 您的代码返回anon类型。 This just returns the object which has the lowest interest. 这只会返回兴趣最低的对象。 The interest data isn't preserved. 兴趣数据不会保留。

Either way, use Min to get the minimum. 无论哪种方式,请使用Min来获取最小值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM