C# - var 到 List转换

发布于 2024-08-07 14:53:08 字数 346 浏览 5 评论 0原文

如何将 var 类型转换/转换为 List 类型?

此代码片段给我错误:

List<Student> studentCollection = Student.Get();

var selected = from s in studentCollection
                           select s;

List<Student> selectedCollection = (List<Student>)selected;
foreach (Student s in selectedCollection)
{
    s.Show();
}

How to cast/convert a var type to a List type?

This code snippet is giving me error:

List<Student> studentCollection = Student.Get();

var selected = from s in studentCollection
                           select s;

List<Student> selectedCollection = (List<Student>)selected;
foreach (Student s in selectedCollection)
{
    s.Show();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

惯饮孤独 2024-08-14 14:53:08

当您执行 Linq to Objects 查询时,它将返回类型 IEnumerable,您可以使用 ToList() 方法从 IEnumerable创建 List

var selected = from s in studentCollection
                           select s;

List<Student> selectedCollection = selected.ToList();

When you do the Linq to Objects query, it will return you the type IEnumerable<Student>, you can use the ToList() method to create a List<T> from an IEnumerable<T>:

var selected = from s in studentCollection
                           select s;

List<Student> selectedCollection = selected.ToList();
北斗星光 2024-08-14 14:53:08

示例代码中的 var 实际上键入为 IEnumerable如果您所做的只是枚举它,则无需将其转换为列表

var selected = from s in studentCollection select s;

foreach (Student s in selected)
{
    s.Show();
}

如果您确实需要将其作为列表,则 ToList() 来自 Linq 的方法会将其转换为您的方法。

The var in your sample code is actually typed as IEnumerable<Student>. If all you are doing is enumerating it, there is no need to convert it to a list:

var selected = from s in studentCollection select s;

foreach (Student s in selected)
{
    s.Show();
}

If you do need it as a list, the ToList() method from Linq will convert it to one for you.

不忘初心 2024-08-14 14:53:08

您可以调用ToList LINQ扩展方法

List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
    s.Show();
}

You can call the ToList LINQ extension Method

List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
    s.Show();
}
子栖 2024-08-14 14:53:08

尝试以下操作

List<Student> selectedCollection = selected.ToList();

Try the following

List<Student> selectedCollection = selected.ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文