本文介绍了哪里了ToList()方法? (IQueryable的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我试试这个,它会工作:

If I try this, it will work:

var query = myContextObject.Users.Where(u=>u.Name == "John");
query.ToList();



我能够调用了ToList 和。很多其他的扩展方法

I'm able to call ToList and a lot of other extension methods.

但是,如果我试试这个:

But if I try this:

public List ConvertQueryToList(IQueryable query)
{
    return query.ToList();
}



了ToList 荣获' T为访问,我猜这是因为了ToList 是一个扩展方法,但随后是了ToList 如何附着在第一实施例?
是否有可能访问了ToList 在第二种情况下?

ToList won't be accessible, I'm guessing this is because ToList is an extension method, but then how is that ToList is attached in the first example?Is it possible to access ToList in the second case?

推荐答案

您需要把它写成:

public List<T> ConvertQueryToList<T>(IQueryable<T> query)
{
    return query.ToList();
}

这将导致的IQueryable< T> 返回相应的列表< T> ,自的方法需要的IEnumerable< T> 为输入(这也适用于的IQueryable< T> ,因为)

This will cause the IQueryable<T> to return the appropriate List<T>, since the Enumerable.ToList() method requires an IEnumerable<T> as input (which also works with IQueryable<T>, as IQueryable<T> inherits IEnumerable<T>).

话虽这么说,实在没有理由使用这种方式。你可以随时拨打了ToList()直接,如果你需要创建一个列表< T> - 的内部抽象第二层只是混淆的API进一步。

That being said, there is really no reason to use it this way. You can always just call ToList() directly if you need to create a List<T> - abstracting inside of a second layer just confuses the API further.

如果你想转换一个非通用的界面,你需要做的是这样的:

If you're trying to convert a non-generic IQueryable interface, you would need to do something like:

public List<T> ConvertQueryToList<T>(IQueryable query)
{
    return query.Cast<T>.ToList();
}

这则需要调用这样的:

var results = ConvertQueryToList<SomeType>(queryable);



另外,如果你要离开这个非一般的(我不推荐),然后你可以使用:

Alternatively, if you want to leave this non-generic (which I wouldn't recommend), then you could use:

public ArrayList ConvertQueryToList(IQueryable query)
{
    ArrayList results = new ArrayList();
    results.AddRange(query.Cast<object>().ToList());
    return results;
}

这篇关于哪里了ToList()方法? (IQueryable的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 17:14