[英]Why does cast from IEnumerable<string> to List<string> fail?
Why does the following not succeed in casting IEnumerable<string>
to List<string>
? 为什么以下不能成功将
IEnumerable<string>
为List<string>
?
var l = new List<Tuple<string, int>>();
l.Add(new Tuple<string, int>("a string", 1));
List<string> s = (List<string>)l.Select(x => x.Item1); // System.InvalidCastException
MessageBox.Show(s[0]);
Also, why is the exception not caught properly in Visual Studio? 另外,为什么Visual Studio中没有正确捕获异常? It appears in the debug window but doesn't stop execution of the program.
它出现在调试窗口中,但不会停止执行程序。
Select
returns an IEnumerable<T>
. Select
返回IEnumerable<T>
。 If you want the results as a List<T>
, use: 如果您希望结果为
List<T>
,请使用:
List<string> s = l.Select(x => x.Item1).ToList()
Internally the Select
method is not generating a List
at all; 在内部,
Select
方法根本不生成List
; the elements are returned on the fly as the IEnumerable<T>
is iterated. 当
IEnumerable<T>
被迭代时,元素会立即返回。
I would except the Exception to be caught. 除了异常之外我会被抓住。 My guess would be that you have a catch (perhaps not one that you added) that is picking it up somewhere along the way.
我的猜测是,你有一个捕获(也许不是你添加的一个),它正在沿途的某个地方捡起它。
It's because your approach is all wrong; 这是因为你的方法都是错的; you can convert the result of a Select into a list - just not like that - simply because it is an IEnumerable not a List .
你可以将Select的结果转换成一个列表 - 只是不喜欢 - 只是因为它是一个IEnumerable而不是List 。 If you want a list then do
如果你想要一个列表,那么
var string_list = l.Select(x => x.Item1).ToList();
If you absolutely, concretely, 100%, certainly know that you only have one element[1] then do: 如果你绝对,具体地说,100%,当然知道你只有一个元素[1]然后做:
var l = new List<Tuple<string, int>>();
l.Add(new Tuple<string, int>("a string", 1));
MessageBox.Show( l.Select(x => x.Item1).First() );
If your list could contain more than one element then do 如果您的列表可能包含多个元素,那么请执行此操作
MessageBox.Show( String.Join(", ", l.Select(x => x.Item1)) );
If you want to work with LINQ effectively it's important to understand what's happening and to realize that what you are creating are somesort of result set - which is not the same as a primitive List and this is where IMO LINQ is incredibly powerful - you just need to understand it. 如果你想有效地使用LINQ,重要的是要了解正在发生的事情,并意识到你正在创建的是一些结果集 - 这与原始List不同,这就是IMO LINQ非常强大的地方 - 你只需要了解它。
1 - In which case why are you working with a list.... 1 - 在哪种情况下你为什么要使用列表....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.