Casting Linq结果无法按预期工作

Joh*_*cht 0 c#

这可能是一个愚蠢的问题,因为我对Linq很新.我创建了一个返回字符串列表的Linq表达式.我可以迭代结果.但是,当我将结果转换为List时,会产生运行时错误.看到这段代码:

class Product { public string name; }

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, Product> p1 = new Dictionary<string, Product>();
        p1["a"] = new Product() { name = "first"} ;
        p1["b"] = new Product() { name = "second" };

        var Y = p1.Values.Select(x => x.name);
        foreach (string s in Y) { Console.WriteLine(s); }

        List<string> ls = (List<string>)p1.Values.Select(x => x.name); // this fails !?
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

Sel*_*enç 8

它失败,因为Select没有返回List.您需要使用ToList来实现您的查询:

 List<string> ls = p1.Values.Select(x => x.name).ToList();
Run Code Online (Sandbox Code Playgroud)

LINQ方法使用延迟执行,这意味着它们不会返回结果,直到您通过迭代(例如使用foreach)或使用某种方法强制迭代(如ToArrayToList方法)来运行查询.

以下是一些有用的读物​​:

  • +如果可能的额外,作为解释完整原因的唯一答案*为什么*演员表无效. (2认同)