9

我在找到正确的语法来完成以下操作时遇到了一些麻烦:

是否可以将 LINQ(Lambda 表达式)用于 .GroupBy 数据,而不是使用通常的 .Sum() 或 .Count() 我希望结果数据是 Int 列表。

我定义了自己的类,名为:Filter_IDs。它的构造函数需要两个参数:

public int? type; // Represents the object_type column from my database
public List<int?> objects; // Represents the object_id column from my database

我想将数据库中的数据加载到这个对象中。以下 LINQ 查询应生成 Filter_ID 列表:

以下 LINQ 查询应生成 Filter_ID 列表:

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

使用此查询不会产生任何构建错误,但会在运行时出现“NotSupportedException”。

数据库看起来像这样可以让您更好地理解数据:

http://d.pr/i/mnhq+(droplr图像)

在此先感谢,格本

4

3 回答 3

12

我认为问题是数据库无法在选择中调用 ToList,也无法创建新的 Filter_ID。

尝试这样的事情:

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();
于 2012-12-06T14:44:11.863 回答
1

也许你想要

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

获取不同的列表objectType并使用它对每个列表进行子查询object_id

但是,对我来说,按顺序枚举值似乎更有效,

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>();   
        }
    }    
}
于 2012-12-06T14:49:16.800 回答
0

您可以在客户端使用 GroupBy:

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();
于 2012-12-06T14:44:35.020 回答