tags:

views:

357

answers:

2
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 do I implement GetMaxValue? I want to give it a property name through a lambda and have GetMaxValue perform a LINQ Max query.

Thanks!

+1  A: 
int num = MyDatas.Select(d => d.Value1).Max();

Edit:

You might want to store the Value as an array instead.

Daniel A. White
Haha, quick on the draw; had to delete mine!
Gurdas Nijor
Thanks for the response. There will be additional logic within the GetMaxValue method that I do not want to duplicate. Any idea how I would do it within the method?
Jim
What do you mean?
Daniel A. White
If the result queried is the max value in MyDatas, return a different value.
Jim
A: 

If you are asking how to use the expression object, you need to compile it first. The compiled expression itself is just a delegate, so you need to pass it the data you need. E.g. here's an example of what you were asking:

    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;
    }
DSO
Thank you - precisely what i was looking for.
Jim