不包含GroupBy

时间:2015-12-16 07:51:32

标签: c# visual-studio func

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();
    }

我试图做这样的事情,但得到一个错误

  

IQueryable<FPSinformation>不包含&#39; GroupBy&#39;的定义   和最好的扩展方法重载   ParallelEnumerable.GroupBy<string, int>(ParallelQuery<string>, Func<string, int>)需要ParallelQuery<string>

类型的接收器

我做错了什么?

修改

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();

这是我尝试优化的实际代码

2 个答案:

答案 0 :(得分:2)

将字符串更改为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;
    }

答案 1 :(得分:2)

此代码存在2个问题。

首先,为了使其编译,groupingFunction应该是Func<FPSinformation, int> - 输入的类型不是string,而是FPSinformation

此更改将使其编译,但编译器将选择Enumerable.GroupBy扩展方法。 Queryable.GroupBy需要Expression<Func>参数,而不是Func - 所以它应该是Expression<Func<FPSinformation, int>>

public List<CardGrouping> GetCardGrouping(IQueryable<FPSinformation> queryable, 
                             Expression<Func<FPSinformation, int>> groupingFunction)

您要按int对其进行分组,因此.Where(x => x.Key != null)没有意义 - x.Key不能为空。