Rino
Rino

Reputation: 41

How Iterate from list of Anonymous Types?

i have this linq to entities query:

c.CreateQuery<T_Hotels>("T_Hotels").Where(item => item.Id > 0).GroupBy(item => new { item.Location, item.Name }).Select(group => new { group.Key, Total = group.Sum(item => item.Id) })

I want to implement everything in a method of a class Helper, how declare the expressions of GroupBy and Select, what return type?

public IQueryable<???> GetHotelsGroupBy(Expression<Func<T_Hotels, bool>> pWhere,
         ??? pGroupBy, ??? pSelect)
{
   return c.CreateQuery<T_Hotels>("T_Hotels").Where(pWhere).GroupBy(pGroupBy).Select(pSelect);

}

Sorry for my English language. Rino

Upvotes: 4

Views: 516

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

public IQueryable<TResult> GetHotelsGroupBy<TKey, TResult>(
    Expression<Func<T_Hotels, bool>> pWhere,
    Expression<Func<T_Hotels, TKey>> pGroupBy, 
    Expression<Func<IGrouping<TKey, T_Hotels>, TResult>> pSelect
)
{
    return c.CreateQuery<T_Hotels>("T_Hotels")
            .Where(pWhere)
            .GroupBy(pGroupBy)
            .Select(pSelect);
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062745

Anonymous types should ideally not be exposed outside of the type that uses them, unless you are happy to use reflection to talk to them. However, you could return the non-generic IEnumerable or IList.

There is something called "cast by example" that can work to get anon-types back to what you expect, but that is very brittle. It would be better (and less work) to declare a custom type to represent the data over this API. Then you aren't fighting the system at every step.

Upvotes: 1

Related Questions