【问题标题】:InvalidCastException when trying to make a list from xml file尝试从 xml 文件创建列表时出现 InvalidCastException
【发布时间】:2015-08-23 08:52:20
【问题描述】:

我正在尝试使用从 xml 文件中读取信息的 MVC 在 Web 应用程序中创建一个表。我正在尝试在将其发送回控制器之前订购此列表,但我的 orderby 行上有一个 InvalidCastException。我做错了什么?

string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/HighScores.xml");
DataSet ds = new DataSet();
ds.ReadXml(xmlData);
var scores = new List<ExternalScoreModel>();

try
{
    scores = (from r in ds.Tables[0].AsEnumerable()
              orderby r.Field<Int32>("Score") descending
              select new ExternalScoreModel
              {
                  Score = Convert.ToInt32(r[0]),
                  FirstName = r[1].ToString(),
                  LastName = r[2].ToString(),
              }).ToList();
}
catch (IndexOutOfRangeException e)
{
    //TODO
}
return scores;

通过将 orderby 移动到选择之后来修复它

scores = (from r in ds.Tables[0].AsEnumerable()
                      select new ExternalScoreModel
                      {
                          Score = Convert.ToInt32(r[0]),
                          FirstName = r[1].ToString(),
                          LastName = r[2].ToString(),
                      }).OrderByDescending(x => x.Score).ToList();

【问题讨论】:

  • 你的 xml 数据是什么样的?
  • 如果我不得不冒险猜测:“分数”被存储为字符串,所以 r.Field&lt;Int32&gt;("Score") 失败,因为没有可用的演员表。使用Convert.ToInt...后必须下单。
  • 为什么不使用 LinqToXML 而不是所有这些 DataSet hoopla?
  • 您应该将您的“已修复”部分设置为单独的答案,以便其他有相同问题的人知道解决方案。

标签: c# xml dataset


【解决方案1】:

“分数”列中的数据很可能不是 Int。仔细检查 XML 文件中的数据。该值也可能丢失或为空,在这种情况下,您可以执行以下操作并分配 0 分或您想要的任何其他值。

 orderby r.Field<Int32?>("Score") == null ? 0 : r.Field<Int32>("Score") descending

【讨论】:

  • 你是对的,“Score”中的数据最初是一个字符串,后来我将它转换为一个int。但实际上我只是在你回复我之前弄清楚了,我只是将 orderby r.Field("Score") 降序,然后在 .ToList() 之前添加了一个 .OrderByDescending
  • 也可以。您也可以将其保留为您拥有它的方式,并将 orderby on score 作为一个字符串,它仍然应该正确排序。
  • @LoganGilmore 这个答案有帮助吗?
  • 是的,我之前并没有完全理解如何正确使用它,但现在我有了更好的理解。我刚刚使用了我找到的修复程序,但我同意你的方法肯定也应该有效。谢谢@AnimalStyle
猜你喜欢
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
相关资源
最近更新 更多