How to pass lambda expressions as parameter in C#

北慕城南 提交于 2021-02-04 19:09:06

问题


I am beginner at using lambda expressions.

I have a list of dealers, foreach dealer I have to calculate grade.

The request is that the grade calculation to be separated into a separate method.

So I am writing the below two methods, however I am unable to pass parameters to CalculateGrade() method,

public IEnumerable<Dealers> GetDealerGrades(IEnumerable<Dealers> gradeData)
{
    return gradeData
        .GroupBy(row => new { row.Name })
        .Select(g => new Dealers
        {
            Name = g.Key.Name,
            TotalPoints = CalculateGrade(x => Convert.ToDouble(x.RecievedPoints),
                                         y => y.MaxPoints,
                                         z => Convert.ToDouble(z.Weightage)) 
        })
        .ToList();
}

private double CalculateGrade(double d1, int d2, double d3)
{
    return ( d1 / d2 ) 
        * d3 == 0.00 ? 1
        : d3;
}

Can somebody advise how to pass parameters in this , or how to pass lamda expressions and calculate grade?

Many thanks in advance...


回答1:


Looks like you need that:

return gradeData
    .GroupBy(row => row.Name)
    .Select(g => new Dealers
    {
        Name = g.Key.Name,
        TotalPoints = g.Sum(x => CalculateGrade(Convert.ToDouble(x.RecievedPoints),
                                                x.MaxPoints,
                                                Convert.ToDouble(x.Weightage)))
    })
    .ToList();

It will call CalculateGrade method on every element from group and sum returned values into TotalPoints property.

Or you can change your CalculateGrade to take IEnumerabale<Dealers>:

private double CalculateGrade(IEnumerable<Dealers> dealers)
{
    // calculations here
    return dealers.Sum(x => CalculateGrade(Convert.ToDouble(x.RecievedPoints),
                                            x.MaxPoints,
                                            Convert.ToDouble(x.Weightage)))
}

And use it in your query:

return gradeData
    .GroupBy(row => row.Name)
    .Select(g => new Dealers
    {
        Name = g.Key.Name,
        TotalPoints = CalculateGrade(g)
    })
    .ToList();



回答2:


This doesn't solve your problem, but it gives you an overview how to send lambdas into methods

You would use Func & Action to pass lambdas into a method

Func

Can have 1 - 15 input parameters and must have an output parameter

Action

Can have 1 - 16 input parameters with no output parameter

ie, how I imagine they do it in EntityFramework for a where predicate

public static List<People> Filter<TEntity>(this List<People> myList, Func<TEntity, TResult> predicate)
{
    return myList.Where(predicate).ToList();
}

the usage would then be something like

myList.Filter(ml => ml.Age > 18);


来源:https://stackoverflow.com/questions/18761080/how-to-pass-lambda-expressions-as-parameter-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!