Reputation: 3885
public struct CardGrouping
{
public string Name { get; set; }
public int Count { get; set; }
}
public List<CardGrouping> GetCardGrouping(IQueryable<Areas.RetailShop.Models.FPSinformation> queryable, Expression<Func<Areas.RetailShop.Models.FPSinformation, string>> groupingFunction)
{
return queryable.GroupBy(groupingFunction)
.Where(x => x.Key != null)
.Select(x => new CardGrouping
{
Name = x.Key,
Count = x.Sum(groupingFunction)
}).ToList();
}
I'm trying to do something like this but getting an Error
IQueryable<FPSinformation>
does not contain a definition for 'GroupBy' and the best extension method overloadParallelEnumerable.GroupBy<string, int>(ParallelQuery<string>, Func<string, int>)
requires a receiver of typeParallelQuery<string>
What I'm doing wrong?
EDIT
var data1 = fpslist.GroupBy(x => x.Ration_Card_Type1)
.Select(x => new
{
CardType_Name = x.Key,
CardType_Count = x.Sum(y => y.Ration_Card_Count1)
}).ToList();
This is the actual code which I'm trying to optimise
Upvotes: 0
Views: 2565
Reputation: 714
Change string to Areas.RetailShop.Models.FPSinformation in fun
public List<CardGrouping> GetCardGrouping(List<Areas.RetailShop.Models.FPSinformation> queryable,
Expression<Func<Areas.RetailShop.Models.FPSinformation, string>> groupingFunction,
Func<Areas.RetailShop.Models.FPSinformation, int> sumFunction)
{
if (queryable.AsQueryable() != null)
{
var data = queryable.AsQueryable().GroupBy(groupingFunction).Where(x => x.Key != null).Select(x => new CardGrouping
{
Name = x.Key == null ? "" : x.Key.ToString(),
Count = x.Sum(sumFunction)
}).ToList();
return data;
}
return null;
}
Upvotes: 2
Reputation: 14894
There are 2 problems with this code.
First, to make it compile, the groupingFunction
should be a Func<FPSinformation, int>
- the type of input is not string
, it's FPSinformation
.
This change will make it compile, but the compiler will choose the Enumerable.GroupBy
extension method. The Queryable.GroupBy
requires an Expression<Func>
parameter, not a Func
- so it should be Expression<Func<FPSinformation, int>>
public List<CardGrouping> GetCardGrouping(IQueryable<FPSinformation> queryable,
Expression<Func<FPSinformation, int>> groupingFunction)
You're grouping it by an int
, so the .Where(x => x.Key != null)
doesn't make sense - x.Key
cannot be null.
Upvotes: 2