I would like to do the following but I don’t think this will work:
.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; }
a. should this work? b. if not, do I need to query for the stories and then sort them by the score?
Yes, that should work if the sequence is a sequence of
Storyitems; what problem are you having? Note that ifScoredoesn’t apply to any instance, it might be worth making it static.Another option is to make the Score() method an instance method on a
Story, or an extension method.Note that this only applies to LINQ-to-Objects; if you are using LINQ-to-SQL / LINQ-to-Entities, etc you either need to use a lambda for the whole thing, or (in LINQ-to-SQL only) use a UDF-mapped function (on the data-context) to calculate the value.
Example (LINQ-to-Objects) with your original syntax:
Add a
this(i.e.Score(this Story s)), and you can use: