简体   繁体   English

我可以在lambda表达式中调用函数吗?

[英]Can I call a function in a lambda expression?

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 Story items; 是的,如果序列是一系列Story项,那么它应该有效; what problem are you having? 你有什么问题? Note that if Score doesn't apply to any instance, it might be worth making it static. 请注意,如果Score不适用于任何实例,则可能值得将其设置为静态。

Another option is to make the Score() method an instance method on a Story , or an extension method. 另一种选择是使Score()方法成为Story或扩展方法的实例方法。

Note that this only applies to LINQ-to-Objects; 请注意,这仅适用于LINQ到对象; 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. 如果您正在使用LINQ-to-SQL / LINQ-to-Entities等,您需要使用lambda来完成整个事务,或者(仅在LINQ-to-SQL中)使用UDF映射函数(在数据上) context)来计算价值。

Example (LINQ-to-Objects) with your original syntax: 使用原始语法的示例(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;
    }
}

Add a this (ie Score(this Story s) ), and you can use: 添加this (即Score(this Story s)并且可以使用:

.OrderByDescending(s=>s.Score())

On a minor note, you may write 在一个小调,您可以写

.OrderByDescending(Score)

since "Score"'s signature fulfills the required signature. 因为“得分”的签名符合要求的签名。

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

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