Passing an expression as a parameter

I'm trying to build a generic GroupBy Method, I guess it should be something like this

var result = GenericGroupBy<List<DTO>>(dataList, g=>g.Id);

public object GenericGroupBy<T>(object data, Func<T, bool> groupByExpression)
{
    return ((List<T>)data).GroupBy(groupByExpression);
}

But I can not make it work.

How to pass expression like g=>g.Id?

Jon Skeet
people
quotationmark

Currently there are two problems:

  • Your method expects a Func<T, bool> and I suspect g => g.Id fails that because your Id property isn't a bool
  • You're currently specifying List<DTO> as the type argument, when I suspect you really want just DTO.

Given your comments, this will work:

var result = GenericGroupBy<DTO>(dataList, g => g.Id);

public object GenericGroupBy<T>(object data, Func<T, int> groupByExpression)
{
    return ((List<T>)data).GroupBy(groupByExpression);
}

... but I'd make it a bit more general unless you always want to group by int:

var result = GenericGroupBy<DTO, int>(dataList, g => g.Id);

public object GenericGroupBy<TElement, TKey>
    (object data, Func<TElement, TKey> groupByExpression)
{
    return ((IEnumerable<TElement>)data).GroupBy(groupByExpression);
}

Note how I've also changed the cast from List<T> to IEnumerable<T> - you don't need it to be a List<T>, so why cast to that?

people

See more on this question at Stackoverflow