【发布时间】: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<Int32>("Score")失败,因为没有可用的演员表。使用Convert.ToInt...后必须下单。 -
为什么不使用 LinqToXML 而不是所有这些 DataSet hoopla?
-
您应该将您的“已修复”部分设置为单独的答案,以便其他有相同问题的人知道解决方案。