2017-02-09 62 views
0

我正在使用MVVM,並且想按升序排序我的ComboBox。 存儲在ObservableCollection中的我的項目(來自數據庫)始終是以字符串形式存儲的數字。c#ComboBox中使用Linq的字符串中的訂單號(ObservableCollection)

一旦我過去10我ComboBox顯示1其次10

我可以調整Linq排序嗎?

或者我嘗試錯了嗎?

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

private void LoadData() 
{ 
    MyCollection = _clsItemsDataService.GetItems(); 
    MyCollection.OrderBy(p => p.Items); 
} 
+2

如果需要,您必須在排序前將字符串轉換爲整數,例如,1 3 9 10而不是1 10 3 9. – itsme86

+3

'int.Parse(p.Items)'? (儘管'Items'看起來像一個單一值*的直覺名稱。) – David

+0

答案在這裏: http://stackoverflow.com/questions/6396378/c-sharp-linq-orderby-numbers-that-are-字符串,你不能將它們轉換爲int –

回答

0

您需要在排序時將字符串轉換爲整數。這是可以做到這樣的:

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

但F你必須要擔心Items可能包含的東西,不能轉換成整數,你想用int.TryParse()

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

OrderByDescending不是實例方法ObservableCollection<T>。它確實對不是進行排序,但返回表示排序序列的新的IEnumerable<T>。這就是爲什麼我從OrderByDescending返回的排序序列創建一個新的ObservableCollection<clsItemsModel>


秒注意:你說你想要的 「上升」 的數字,而是用OrderByDescending。我複製了那部分,也許你想用OrderBy代替。

+0

這工作!是的,使用OrderByDescending是一個錯誤,因爲我試圖看看組合框會做什麼。忘了改回它。 –