我在找到正确的语法来完成以下任务时遇到了一些麻烦:
LINQ(Lambda Expression)是否可以使用.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();
使用此查询不会产生构建错误,但会在RunTime上显示“NotSupportedException”。
数据库看起来像是为了让您更好地了解数据:
http://d.pr/i/mnhq+(droplr image)
提前致谢, 戈
答案 0 :(得分:11)
我认为问题是数据库无法在select中调用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();
答案 1 :(得分: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>();
}
}
}
答案 2 :(得分: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();