关于c#:从IQueryable转换为IEnumerable


Converting from IQueryable to IEnumerable

如何从IQueryable转换为IEnumerable?我看了从iqueryable到IEnumerable的另一篇文章,但是它不够通用,不能重用?有人能提供一种通用的、可重用的方法来实现这一点吗?

1
2
3
4
5
6
7
8
9
10
11
public class SoftwareProductRepository
{
    BitDatabaseEntities bitDB = new BitDatabaseEntities();
    public IEnumerable<BuildMetrics> GetBuildMetrics()
    {

        var list = (from r in bitDB.bit_sanity_results select r);

        return list;
    }
}

错误信息:

Cannot implictly converty type
'System.Linq.IQueryable'
to
'System.Collections.IEnumerable'.An
explicit conversion exists(are you missing a cast?)


尝试将Queryable转换为Enumerable,方法如下:

1
(from r in bitDB.bit_sanity_results select r).AsEnumerable();

这将给您一个可枚举的集合,但我认为您可能需要从这个返回的bit_sanity_results生成BuildMetrics对象。像:

1
2
3
(from r in bitDB.bit_sanity_results select new BuildMetrics{
       <some BuildMetrics property>=r.<some bit_sanity_results property>
        }).AsEnumerable();

例子

1
2
3
4
5
public class ReturnClass
{
    public string SSId{get;set;}
    public string Name{get;set;}
}

我们从中选择的表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
table values_store
(
    ss_id varchar(50),
    user_name varchar(250)
)

public class ReturnValuesRepository
{
    public IEnumerable<ReturnClass> GetReturnClasses()
    {  
        //As commented by @Enigmativity if your `BitDatabaseEntities` is `IDisposable` (sure if it inherits from `DbContext`) you should wrap it in a `using` block
        using(var db = new ValuesEntities())
        {
            var list = (from r in db.values_store select new
                   ReturnClass
                     {
                         SSId=r.ss_id,
                         Name=r.user_name
                    }).AsEnumerable();

            return list;
        }
    }
}


在这种情况下,转换实际上应该是隐式的,因为IQueryable实现IEnumerable

这里的问题是类型不匹配,因为您正在获取IQueryable,但正在尝试返回IEnumerable

您需要将IQueryable投影到IEnumerable

像这样:

1
2
3
4
5
6
7
8
public class SoftwareProductRepository
{
    BitDatabaseEntities bitDB = new BitDatabaseEntities();
    public IEnumerable<BuildMetrics> GetBuildMetrics()
    {
        return bitDB.bit_sanity_results.Select(r => new BuildMetrics(...));
    }
}