空 Linq 值
我无法让它发挥作用。 State 字段在某些情况下为空,我试图让结果返回“--”(如果它为空或不存在)。
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select new BondData()
{
CUSIP = c.Element("CUSIP").Value,
Description = (string)c.Element("ISSUER").Value,
Maturity= c.Element("MATURITYDT").Value,
AskYield = float.Parse(c.Element("ASKYIELD").Value),
State = (string)c.Element("STATE").Value ?? "--"
}
;
这只是不想工作。我收到的错误是:
NullReferenceException 未处理。 {“对象引用未设置为对象的实例。”}
我知道它不存在。我以为把 ??如果 c.Element("STATE").Value 为 null,则“--”
将返回“--”。
我可以将语句修改为:
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select c;
foreach(var t in CusipFields)
{
switch(t.name)
{
}
}
但我认为它比较慢。这不是我想要的。
I cant get this to work. The State field is empty on certain occassions, I am trying to get the result to return "--" if it is empty, or doesn't exist.
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select new BondData()
{
CUSIP = c.Element("CUSIP").Value,
Description = (string)c.Element("ISSUER").Value,
Maturity= c.Element("MATURITYDT").Value,
AskYield = float.Parse(c.Element("ASKYIELD").Value),
State = (string)c.Element("STATE").Value ?? "--"
}
;
This just doesn't want to work. The error I am getting is:
NullReferenceException was unhandled. {"Object reference not set to an instance of an object."}
I KNOW that it does not exist. I thought that putting ?? "--"
will return "--" if c.Element("STATE").Value is null.
I can resort to modifying the statement to:
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select c;
foreach(var t in CusipFields)
{
switch(t.name)
{
}
}
But I think that it is slower. And its not what I want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用这个:
而不是
我的答案假设,你的问题是,
STATE
元素丢失,而不是空。请告诉我,这是否解决了您的问题。Use this:
instead of
My answer assumes, that your problem is, that the
STATE
element is missing, not empty. Please tell me, whether or not that fixed your problem.我认为这是因为
c.Element("STATE")
为 null,而不是 Value 属性。尝试:
(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";
I think it's because
c.Element("STATE")
is null, not it's Value property.try:
(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";
您收到此错误不是因为
Value
属性为 null,而是因为c.Element(...)
为 null。您需要检查所有Element()
调用中是否存在空值,并采取适当的操作以避免此错误。You're getting this error not because the
Value
property is null, but becausec.Element(...)
is null. You'll need to check for nulls in all of yourElement()
calls and take appropriate action in order to avoid this error.