0

I have an IList in C#, to be sorted in order according to a number. The problem is with numbers higher than 10 (ex: {11,12,13}). They are sorted before numbers less than 10 (ex: {6,7,8}), so at the end of the sorting I get the model with 11 in the first position, and other models with 6 or 7 in the last positions.

I do pass this order number as a string, I am not sure if this is the problem or if I have written the code wrong. Any suggestions?

Code:

IList<TestGrid> myList = new List<TestGrid>();
foreach (DataRow row in Browse.GridNodes.Rows)
{
    TestGrid model = new TestGrid();
    model.Name = row["Name"].ToString();
    model.Type = row["Type"].ToString();
    model.NodeId = row["NodeId"].ToString();
    model.ActivOrderNo = ReadAttribute(row["NodeId"].ToString()+".CONFIG.OrderNumber", 13);
    myList.Add(model);
}

IList<TestGrid> sortedList = myList.OrderBy(r => r.ActivOrderNo).ToList();
CarenRose
  • 1,266
  • 1
  • 12
  • 24
KamalF
  • 105
  • 1
  • 3
  • 19
  • This is what you mean? `List sortedList = myList.OrderBy(r => int.Parse(r.ActivOrderNo.Replace(".CONFIG.OrderNumber", ""))).ToList();` – Arghya C Oct 05 '15 at 14:39
  • No ".CONFIG:OrderNumber" part is just used in the method to get the data from the database, then i want to sort it according to their order – KamalF Oct 05 '15 at 14:49

1 Answers1

1

You should convert this value to a numeric type. For example, if your data allows it, an integer.

List<TestGrid> sortedList = myList.OrderBy(r => Convert.ToInt32(r.ActivOrderNo)).ToList();

At the moment, your sorting is happening on the string "12" vs "1" but it sounds like you actually want to sort on the value of the number inside the string.

TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
  • Yes, exactly, but then when i use Convert.ToInt32 the list for some reason is not passing as json to the Grid. So it does not appear in the view ! and this is because an exception takes place "Input string was not in a correct format." – KamalF Oct 05 '15 at 14:52
  • In that case, some of the data isn't integers - possibly some are null or have fraction values? You can replace the Convert.ToInt32 with your own function to get the numeric value of the string that you have though. – TomDoesCode Oct 05 '15 at 14:54
  • The answer was right but i had some null values and other strings from the database, i fixed it and it worked. thanks – KamalF Oct 05 '15 at 15:39