【问题标题】:C# - var to List<T> conversionC# - var 到 List<T> 的转换
【发布时间】:2010-12-05 19:05:00
【问题描述】:

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

这段代码 sn-p 给了我错误:

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();
}

【问题讨论】:

  • var 不是类型,它只是您分配给变量的任何表达式类型的占位符。在这种情况下,查询表达式的计算结果为 IEnumerable&lt;Student&gt;

标签: list c#-3.0 var


【解决方案1】:

当您执行 Linq to Objects 查询时,它会返回类型 IEnumerable&lt;Student&gt;,您可以使用 ToList() 方法从 IEnumerable&lt;T&gt; 创建一个 List&lt;T&gt;

var selected = from s in studentCollection
                           select s;

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

【讨论】:

【解决方案2】:

示例代码中的var 实际上输入为IEnumerable&lt;Student&gt;如果你只是枚举它,则无需将其转换为列表

var selected = from s in studentCollection select s;

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

如果你确实需要它作为一个列表,来自 Linq 的 ToList() 方法会为你将它转换为一个。

【讨论】:

    【解决方案3】:

    您可以调用 ToList LINQ 扩展方法

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

    【讨论】:

      【解决方案4】:

      试试下面的

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        相关资源
        最近更新 更多