LINQ Lambda, Group by with list

人盡茶涼 提交于 2019-12-05 03:31:44

I think the problem is the DB is not able to call ToList in the select, nor to create a new Filter_ID.

Try something like this :

List<Filter_IDs> filterids = ef.filterLine.Select(o => new { objectType = o.objectType, object_id=o.object_id})
    .GroupBy(fl => fl.objectType).ToList()
    .Select(fl => new Filter_IDs { type = fl.Key, objects = fl.Select(x => x.object_id).ToList() })
    .ToList();

Maybe you want

IList<Filter_IDs> filterIds = ef.filterline
    .Select(fl => fl.objectType).Distinct()
    .Select(ot => new Filter_IDs
        {
            type = ot,
            objects = ef.filterline
                          .Where(fl => fl.objectType == ot)
                          .Select(fl =>objectType)
                          .ToList()
        }).ToList();

Get the distinct list objectType and use that to subquery for each list of object_id.

However, it seems more efficient to me to just enumerate the values in order,

var results = new List<Filter_IDs>();
var ids = new List<int>();
var first = true;
int thisType;

foreach (var fl in ef.filterLines
                       .OrderBy(fl => fl.objectType)
                       .ThenBy(fl => fl.object_Id))
{
    if (first)
    {
        thisType = fl.objectType;
        first = false;
    }
    else
    {
        if (fl.objectType == thisType)
        {
            ids.Add(fl.object_Id);
        }
        else
        {
           results.Add(new Filter_IDs
                {
                    Type = thisType,
                    objects = ids
                });
           thisType = fl.objectType;
           ids = new List<int>();   
        }
    }    
}

You can use GroupBy on client side:

List<Filter_IDs> filterids = ef.filterLine
        .Select(fl=>new {fl.ObjectType, fl.object_id})
        .AsEnumerable()
        .GroupBy(fl => fl.objectType)
    .Select(fl => new Filter_IDs { type = fl.Key, objects = fl.Select(x => x.object_id).ToList() })
    .ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!