InvalidCastException when trying to make a list from xml file

222 views Asked by At

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

There are 1 answers

4
Animal Style On

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