简体   繁体   中英

InvalidCastException when trying to make a list from xml file

I'm trying to make a table in a web application using MVC that reads information from an xml file. I'm trying to order this list before sending it back to the controller but there is an InvalidCastException on my orderby line. What am I doing wrong?

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;

Fixed it by moving the orderby until after the select

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();

The data in the "Score" column is most likely not an Int. Double check the data in the XML file. The Value may also be missing or is null in which case you can do something like the below and assign a score of 0 or whatever else you would want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM