0

I am using MVVM and I want to sort my ComboBox by ascending numbers. My items (from database) stored in an ObservableCollection are always numbers stored as string.

Once I go past 10 my ComboBox shows 1 followed by 10.

Can I adjust the Linq to sort correctly?

Or am I trying it wrong?

public ObservableCollection<clsItemsModel> MyCollection
{
    get { return _MyCollection; }
    set
    {
        _MyCollection = value;
        RaisePropertyChanged();
    }
}

private void LoadData()
{
    MyCollection = _clsItemsDataService.GetItems();
    MyCollection.OrderBy(p => p.Items);
}
  • 2
    You have to convert the strings to ints before sorting if you want, for instance, 1 3 9 10 instead of 1 10 3 9. – itsme86 Feb 09 '17 at 15:48
  • 3
    `int.Parse(p.Items)`? (Though `Items` seems like an unintuitive name for *a single value*.) – David Feb 09 '17 at 15:51
  • Answer is here: http://stackoverflow.com/questions/6396378/c-sharp-linq-orderby-numbers-that-are-string-and-you-cannot-convert-them-to-int – Leszek P Feb 09 '17 at 15:52
  • Items was used as an example :) it was a value in my own language – Jurgen Volders Feb 09 '17 at 16:03

1 Answers1

0

You need to convert the strings to integers while sorting. This can be done like that:

MyCollection = new ObservableCollection<clsItemsModel>(_clsItemsDataService.GetItems()
                                   .OrderByDescending(p => Convert.ToInt32(p.Items)));

But f you have to be afraid that Items may contain things that cannot be converted to integers, you'd rather use int.TryParse():

MyCollection = new ObservableCollection<clsItemsModel>(_clsItemsDataService.GetItems()
                   .OrderByDescending(p => 
                   {
                       int n;
                       return int.TryParse(p.Items, out n) ? n : int.MinValue;
                   }));

Note that OrderByDescending is not an instance method of ObservableCollection<T>. It does not sort that instance, but returns a new IEnumerable<T> that represents the sorted sequence. Thatswhy I create a new ObservableCollection<clsItemsModel> from the sorted sequence returned by OrderByDescending.


Second note: you said you want "ascending" numbers, but use OrderByDescending. I copied that part, maybe you want to use OrderBy instead.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • THIS WORKED!!! Yes that was a mistake using the OrderByDescending because i was trying to see what the combobox would do then. Forgot to change it back. – Jurgen Volders Feb 09 '17 at 16:10