When I run this code
var res = from name in Util.Cmd (@"dir")
where name[0] == '1'
select name;
res.Dump();
I get a directory listing, then an IndexOutofBoundsException
when the res.Dump()
line is evaluated. I was expecting to see a directory listing followed by another listing showing only the lines where the first character is a 1
.
However, if I run:
var res = from name in Util.Cmd (@"dir")
where name.Length > 1 && name[0] == '1'
select name;
res.Dump();
I get the expected behaviour (i.e. all lines greater than 1 in length and starting with 1
). No exception is thrown.
So my question is, why does the first code segment result in an exception?
The where name[0] == '1'
clause isn't actually evaluated until you run the Dump
command. Before then it's just a delay executed query. The problem is one of the values returned by Util.Cmd
is the empty string and hence you get an IndexOutOfBoundsException