LINQ Lambda,分组与列表 [英] LINQ Lambda, Group by with list

查看:168
本文介绍了LINQ Lambda,分组与列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having some trouble with finding the right syntax to accomplish the following:

可能使用LINQ(Lambda表达式)到.GroupBy数据,而不是使用通常的.Sum()或.Count()我想得到的数据是Int的列表。

Is it possible with LINQ (Lambda Expression) to .GroupBy data and instead of using the usual .Sum() or .Count() I want the resulting data to be a List of Int.

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

I defined my own class named: Filter_IDs. Its constructor needs two parameters:

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_IDs列表:

I want to load data from my database into this object. The following LINQ query should result in a List of Filter_IDs:

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

The following LINQ query should result in a List of Filter_IDs:

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。

Using this query gives no building error but gives an 'NotSupportedException' on RunTime.

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

The database looks like this to give you a better understanding of the data:

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

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

提前感谢,
Gerben

Thanks in advance, Gerben

推荐答案

我认为问题是DB不能在select中调用ToList,创建一个新的Filter_ID。

I think the problem is the DB is not able to call ToList in the select, nor to create a new 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();

这篇关于LINQ Lambda,分组与列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆