How to write a LINQ expression that will return the maximum field value?

public class MyData
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Value3 { get; set; }
}

public class MyViewData
{
    List<MyData> MyDatas = new List<MyData>();

    public int GetMaxValue(Expression<Func<MyData, int>> action) {
        // get highest value of specified field in MyDatas, return value
        // pseudo code of what i'm looking for would be:
        // return action.Max()
    }

    public void Test() {
        int num = GetMaxValue(d => d.Value1);
    }
}

How to implement GetMaxValue? I want to give it the name of the property via lambda and GetMaxValue to execute the LINQ Max query.

Thanks!

+3
source share
2 answers

If you ask how to use an expression object, you need to compile it first. The compiled expression itself is just a delegate, so you need to pass the data you need to it. For example. here is an example of what you asked:

    public int GetMaxValue(Expression<Func<MyData, int>> action)
    {
        if (MyDatas.Count == 0)
        {
            throw new InvalidOperationException("Sequence contains no elements");
        }

        Func<MyData, int> func = action.Compile();

        int max = int.MinValue;

        foreach (MyData data in MyDatas)
        {
            max = Math.Max(max, func(data));
        }

        return max;
    }
+1
source
int num = MyDatas.Select(d => d.Value1).Max();

Edit:

Instead, you can save Valueas an array.

+2
source

Source: https://habr.com/ru/post/1720022/


All Articles