本文介绍了简单方法*在LINQ查询中转换对象?不是*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灵感来自Albahari第8章的优秀C#3.0 in a Nutshell

(这本书太棒了,你必须得到它,如果你必须买一个C#

book)以及Jon Skeet的书的附录A,我将通过

一些LINQ查询。但是如何施展? (


见下面的内容,修改自别人的代码。


问题是查询''停止''(抛出一个演员例外)在3,并且

永远不会到达紫罗兰。


如何防止这种情况?


Pseudocode好的,只需要一个提示就可以了,但更多的当然是

更好。


RL


* PS - 通过简单的方式来投射我的意思是非常简短,可以在运行时工作,而不是像列出所有的CASE / SWITCH语句

可能提前,但是,我会得到所有答案。


//

List< objectwords = new List< object {" green"," blue",3," violet",

5};


//投放对象列表中键入''string''

//并投射每个字符串的前两个字母。


尝试

{

IEnumerable< strin gquery =

words.AsQueryable()。Cast< string>()。选择(str = str.Substring(0,2));


foreach (查询中的字符串s)

Console.WriteLine(s);

}


catch(ArgumentException ex)

{

Console.WriteLine(ex);

}

catch(InvalidCastException ex2)

{

Console.WriteLine(" invalid cast!" + ex2);

}


/ *此代码*应*生成以下输出,但

它突破了查询到达上面的''3'并抛出一个

InvalidCastException - 如何让它完成查询直到

结束?


gr

bl

vi

* /


RL

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<objectwords = 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<stringquery =
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

推荐答案




请参阅OfType方法。


-

Jon Skeet - < sk *** @ pobox.com>

网站:

博客:

C#深度:

See the "OfType" method.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com



这篇关于简单方法*在LINQ查询中转换对象?不是*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:35