C# 如何使参数接受(x=>x.Value),比如.Sum(x=>x.Value)或.Average(x=>x.Value)

C# 如何使参数接受(x=>x.Value),比如.Sum(x=>x.Value)或.Average(x=>x.Value),c#,lambda,extension-methods,C#,Lambda,Extension Methods,如何使参数接受x=>x.Value,比如.Sumx=>x.Value或.Averagex=>x.Value。我想我需要一个函数,但我不确定。我不知道方法签名应该是什么样子 以下是我当前的扩展方法: public static double StdDev(this IEnumerable<double> values) { //code } 这是我到目前为止的重载扩展,我知道这是不对的: public static double StdDev(this IEnumerable

如何使参数接受x=>x.Value,比如.Sumx=>x.Value或.Averagex=>x.Value。我想我需要一个函数,但我不确定。我不知道方法签名应该是什么样子

以下是我当前的扩展方法:

public static double StdDev(this IEnumerable<double> values)
{
    //code
}
这是我到目前为止的重载扩展,我知道这是不对的:

public static double StdDev(this IEnumerable<double> values, Func<double, bool> filter)
{
    IEnumerable<double> data;
    if (filter != null)
    {
        data = values.Where(filter);
    }
    else
    {
        data = values;
    }
    return data.StdDev();
}
下面是我的单元测试:

[TestClass]
public class IEnumerableExtensions_StdDev
{
    [TestMethod]
    public void StdDev_Success_Lambda()
    {
        var dataSet = new List<TestType> {new TestType(35.2), new TestType(54.43)};

        //This Line compiles fine but the following one does not.
        var test = dataSet.Sum(x => x.Value);
        var stdev = dataSet.StdDev(x => x.Value);

        stdev.Should().BeInRange(13.5, 13.6);
    }
}

public class TestType
{
    public double Value { get; set; }

    public TestType(double value)
    {
        Value = value;
    }
}
单元测试不编译。它给了我一个错误,如下所示:

“List”不包含“StdDev”的定义,最佳扩展方法重载“IEnumerableExtensions.StdDevIEnumerable,Func”需要“IEnumerable”类型的接收器


我不想更改测试我想更改重载方法签名和/或正文,但我不明白我需要在代码中更改什么才能使其正常工作。

您可以使用第二个默认值为null的参数。我很确定C编译器会将其转换为重载方法,但无论如何,您都可以在代码中使用单个方法来完成。您需要在代码中说明该默认值

public static double StdDev(this IEnumerable<double> values, Func<double, bool> filter = null)
{
    List<double> data;
    if(filter != null)
    {
        data = values.Where(x => filter(x)).ToList();
    }
    else
    {
        data = values.ToList();
    }
    
    //code
}