[英]C# List.AsQueryable() returns System.Collections.Generic.List instead of IQueryable
I have a list of objects List<Student>
that I want return as an IQueryable<Student>
.我有一个对象
List<Student>
我想将其作为IQueryable<Student>
返回。
When I try to use .AsQueryable()
on the list to convert it to IQueryable<Student>
I got a System.Collections.Generic.List`1[ConsoleApp.Student]
.当我尝试在列表中使用
.AsQueryable()
将其转换为IQueryable<Student>
时,我得到了一个System.Collections.Generic.List`1[ConsoleApp.Student]
。
How I can convert list to IQueryable()
?我如何将列表转换为
IQueryable()
?
See below I minimum reproducible example:请参阅下面的最小可重现示例:
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
var students = new List<Student>() ;
students.Add(new Student() { Id = 1, Name = "J" });
students.Add(new Student() { Id = 2, Name = "X" });
IQueryable<Student> queryable = students.AsQueryable();
Console.WriteLine("Hello, World!");
}
}
}
.AsQueryable()
returns a EnumerableQuery<T>
that wraps the list (or IEnumerable<T>
to be precise) and provides the IQueryable interface. .AsQueryable()
返回一个包装列表的EnumerableQuery<T>
(或准确地说是IEnumerable<T>
)并提供 IQueryable 接口。 So if you just want an IQueryable<T>
your don't need to do anything more.因此,如果您只想要一个
IQueryable<T>
,则无需执行任何其他操作。 Your example already demonstrates this perfectly well.您的示例已经很好地证明了这一点。
Note that, the .ToString()
-method on EnumerableQuery just seem to call the underlying collection, so it will still print {System.Collections.Generic.List1[ConsoleApp.Student]}
in the debugger, or when converting it to string.请注意,EnumerableQuery 上的
.ToString()
方法似乎只是调用底层集合,因此它仍会在调试器中或在将其转换为字符串时打印{System.Collections.Generic.List1[ConsoleApp.Student]}
。 I suspect this is why you are confused.我怀疑这就是你感到困惑的原因。 You can call
.GetType().Name
to get the actual typename of an object.您可以调用
.GetType().Name
来获取 object 的实际类型名称。
The larger question is, why do you want a IQueryable?更大的问题是,为什么需要 IQueryable? This is mostly intended to query databases.
这主要用于查询数据库。 If you have objects in memory you usually just use
IEnumerable<T>
.如果您在 memory 中有对象,您通常只使用
IEnumerable<T>
。 If you just want to print your students, Overload.ToString on the student object and call string.Join to produce a string for all students.如果您只想打印您的学生,请在学生 object 上 Overload.ToString 并调用string.Join为所有学生生成一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.