如何优化此 LINQ 扩展方法
我编写了一个自定义排序 LINQ 扩展方法,如下所示,但我认为它可以针对大型结果进行优化。
这是代码:
public static IEnumerable<T> OrderByAncesty<T>(this IEnumerable<T> source, Func<T, DateTime> dateSelector, Func<T, float> scoreSelector)
{
var original = source.ToList();
var maxDate = source.Max(dateSelector);
var list = from p in original
let date = dateSelector(p)
let score = scoreSelector(p)
let date1 = date.ToOADate()
let date2 = maxDate.ToOADate()
let ancesty = (1 - (float)date1 / (float)date2) * score
select new
{
TObject = p,
Ancesty = ancesty
};
return list.OrderBy(p => p.Ancesty).Select(p => p.TObject);
}
I wrote a custom ordering LINQ extension method as below but I think it can be optimized for large results.
Here is the code :
public static IEnumerable<T> OrderByAncesty<T>(this IEnumerable<T> source, Func<T, DateTime> dateSelector, Func<T, float> scoreSelector)
{
var original = source.ToList();
var maxDate = source.Max(dateSelector);
var list = from p in original
let date = dateSelector(p)
let score = scoreSelector(p)
let date1 = date.ToOADate()
let date2 = maxDate.ToOADate()
let ancesty = (1 - (float)date1 / (float)date2) * score
select new
{
TObject = p,
Ancesty = ancesty
};
return list.OrderBy(p => p.Ancesty).Select(p => p.TObject);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个“let”子句都增加了额外的授权级别。您可以通过删除它们来稍微改进一些东西。您也不需要匿名类型 - 或者很可能不需要
ToList()
调用。此外,每次都在maxDate
上调用ToOADate()
是没有意义的。请注意,如果没有“let”子句,它就很清楚了。
Each "let" clause adds an extra level of delegation. You can improve things somewhat by removing them. You also don't need the anonymous type - or quite possibly the
ToList()
call. Additionally, there's no point in callingToOADate()
onmaxDate
every time.It's note as clear without the "let" clauses, mind you.