R
raylopez99
Inspired by Chapter 8 of Albahari's excellent C#3.0 in a Nutshell
(this book is amazing, you must get it if you have to buy but one C#
book) as well as Appendix A of Jon Skeet's book, I am going through
some LINQ queries. But how to cast? (
See the below, modified from somebody else's code.
The problem is the query 'stops' (throws a cast exception) at "3", and
never gets to "violet".
How to prevent this?
Pseudocode OK, just a hint is all I need, but more of course is
better.
RL
*PS--by "easy way to cast" I mean something very short, that can work
at runtime, not something like a CASE/SWITCH statement that lists all
possibilities ahead of time, but, I'll take all answers.
//
List<object> words = new List<object> { "green", "blue", 3, "violet",
5 };
// Cast the objects in the list to type 'string'
// and project the first two letters of each string.
try
{
IEnumerable<string> query =
words.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
foreach (string s in query)
Console.WriteLine(s);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex);
}
catch (InvalidCastException ex2)
{
Console.WriteLine("invalid cast!" + ex2);
}
/* This code *should* produce the following output, but
it breaks out of the query when it gets to '3' above and throws an
InvalidCastException--how to get it to complete the query until the
end?
gr
bl
vi
*/
RL
(this book is amazing, you must get it if you have to buy but one C#
book) as well as Appendix A of Jon Skeet's book, I am going through
some LINQ queries. But how to cast? (
See the below, modified from somebody else's code.
The problem is the query 'stops' (throws a cast exception) at "3", and
never gets to "violet".
How to prevent this?
Pseudocode OK, just a hint is all I need, but more of course is
better.
RL
*PS--by "easy way to cast" I mean something very short, that can work
at runtime, not something like a CASE/SWITCH statement that lists all
possibilities ahead of time, but, I'll take all answers.
//
List<object> words = new List<object> { "green", "blue", 3, "violet",
5 };
// Cast the objects in the list to type 'string'
// and project the first two letters of each string.
try
{
IEnumerable<string> query =
words.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
foreach (string s in query)
Console.WriteLine(s);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex);
}
catch (InvalidCastException ex2)
{
Console.WriteLine("invalid cast!" + ex2);
}
/* This code *should* produce the following output, but
it breaks out of the query when it gets to '3' above and throws an
InvalidCastException--how to get it to complete the query until the
end?
gr
bl
vi
*/
RL