我想做以下但我认为这不会起作用:
.OrderByDescending(s => score(s)),... private double score(Story s) { DateTime now = DateTime.Now; TimeSpan elapsed = now.Subtract(s.PostedOn); double daysAgo = elapsed.TotalDays; return s.Votes.Count + s.Comments.Count - daysAgo; }
一个.这有用吗?
湾如果没有,我是否需要查询故事,然后按分数对它们进行排序?
解决方法
是的,如果序列是一系列Story项目,这应该有效;你有什么问题?请注意,如果score不适用于任何实例,则可能值得将其设置为静态.
另一种选择是使score()方法成为Story或扩展方法的实例方法.
请注意,这仅适用于LINQ到对象;如果您正在使用LINQ-to-sql / LINQ-to-Entities等,您需要使用lambda来完成整个事务,或者(仅在LINQ-to-sql中)使用UDF映射函数(在数据上) context)来计算价值.
使用原始语法的示例(LINQ到对象):
using System.Linq; using System; class Story { // declare type public DateTime PostedOn { get; set; } // simplified purely for convenience public int VotesCount { get; set; } public int CommentsCount { get; set; } } static class Program { static void Main() { // dummy data var data = new[] { new Story { PostedOn = DateTime.Today,VotesCount = 1,CommentsCount = 2},new Story { PostedOn = DateTime.Today.AddDays(-1),VotesCount = 5,CommentsCount = 22},new Story { PostedOn = DateTime.Today.AddDays(-2),VotesCount = 2,CommentsCount = 0} }; var ordered = data.OrderByDescending(s=>score(s)); foreach (var row in ordered) { Console.WriteLine(row.PostedOn); } } private static double score(Story s) { DateTime now = DateTime.Now; TimeSpan elapsed = now.Subtract(s.PostedOn); double daysAgo = elapsed.TotalDays; // simplified purely for convenience return s.VotesCount + s.CommentsCount - daysAgo; } }
添加一个(即分数(此故事)),您可以使用:
.OrderByDescending(s=>s.score())