devtunis
devtunis

Reputation: 141

Sort ObservableCollection in Combobox C# WPf

I want to set sorted the ObservableCollection in combobox,

my result without sorted:

enter image description here

my ViewModel:

 private ObservableCollection<IdentificationSystemType> codeTypeEnum;
   public IdentificationSystemType CodeType
     {
         get { return codeType; }
         set { codeType = value;
         OnPropertyChanged("CodeType");
         }
     }
     
       public NewIdentificationSystemViewModel()
    {
        _identificationToAdd = new IdentificationSystem();
        identificationDeviceToAdd = new IdentificationDevice();
       
        _resetIdentificationCmd = new RelayCommand<string>(resetIdentification);
        saveCommand = new RelayCommand<string>(addFunc, canSave);         
         codeTypeEnum = new ObservableCollection<IdentificationSystemType>(Enum.GetValues(typeof(IdentificationSystemType)).Cast<IdentificationSystemType>());
              }

I had try with var ordered = codeTypeEnum.OrderBy(x => x); but nothing ..it is the same my Enum declaration:

 public enum IdentificationTypes : int
   {
    TerminalEntryGate = 1,
    TerminalExitGate = 2,
    LoadingAreaEntryGate = 3,
    LoadingAreaExitGate = 4,
    IslandEntryGate = 5,
    IslandExitGate = 6,
    BayEntryGate = 7,
    BayExitGate = 8,
    ScalingAreaEntryGate = 9,
    ScalingAreaExitGate = 10,
    OfficeAreaEntryGate = 11,
    OfficeAreaExitGate = 12,
    TankFarmEntryGate = 13,
    TankFarmExitGate = 14,
    StagingAreaEntryGate = 15,
    StagingAreaExitGate = 16,      
    LoadingBayIdentification = 21,
    LoadingArmIdentification = 22,
    LoadingIslandIdentification = 23,        
    PresetIdentification = 27
  }


   

 

How can I fix that? thanks,

Upvotes: 0

Views: 286

Answers (2)

NtFreX
NtFreX

Reputation: 11357

As your enum is of type int you are ordering your collection by those numbers. If you want to order your collection alphabetically you need to parse the integers to strings first.

You can do this in the key selector function you are giving the OrderBy method.

var values = Enum.GetValues(typeof(IdentificationTypes)).Cast<IdentificationTypes>();
var valueList = new ObservableCollection<IdentificationTypes>(values);
var orderedList = valueList.OrderBy(x => x.ToString());

Upvotes: 1

mjwills
mjwills

Reputation: 23898

Change:

codeTypeEnum = new ObservableCollection<IdentificationSystemType>(Enum.GetValues(typeof(IdentificationSystemType))
.Cast<IdentificationSystemType>());

to:

codeTypeEnum = new ObservableCollection<IdentificationSystemType>(Enum.GetValues(typeof(IdentificationSystemType))
.Cast<IdentificationSystemType>().OrderBy(x => x.ToString()));

to force it to be ordered alphabetically.

Upvotes: 1

Related Questions