1

I have a dataset table, I want to group it by column MOID, and then within this group I want to select the row which has max value of column radi.

Can anybody show me how to do it via LINQ to dataset?

ekad
  • 14,436
  • 26
  • 44
  • 46
user424493
  • 51
  • 1
  • 4

3 Answers3

6

Although the solution posted by Barry should work (with a few fixes), it is sub-optimal : you don't need to sort a collection to find the item with the maximum value of a field. I wrote a WithMax extension method, which returns the item with the maximum value of the specified function :

    public static T WithMax<T, TValue>(this IEnumerable<T> source, Func<T, TValue> selector)
    {
        var max = default(TValue);
        var withMax = default(T);
        bool first = true;
        var comparer = Comparer<TValue>.Default;
        foreach (var item in source)
        {
            var value = selector(item);
            int compare = comparer.Compare(value, max);

            if (compare > 0 || first)
            {
                max = value;
                withMax = item;
            }
            first = false;
        }
        return withMax;
    }

It iterates the collection only once, which is much faster than sorting it just to get the first item.

You can then use it as follows

var query =
    from row in table.AsEnumerable()
    group row by row.Field<int>("MOID") into g
    select g.WithMax(r => r.Field<int>("radi"));
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
2

This is untested but I think something like this should work:

        var qry = from m in [YourDataSource]
                      group p by m.MOID into grp
                      select grp.OrderByDescending(a => a.RADI).First();
codingbadger
  • 42,678
  • 13
  • 95
  • 110
0

this works with one query!

public static T WithMax<T, TValue>(this IEnumerable<T> source, Func<T, TValue> keySelector)
{
    return source.OrderByDescending(keySelector).FirstOrDefault();
}
Paolo Sanchi
  • 783
  • 9
  • 19