2012-09-19 140 views
0

我有一個用下面的代碼填充的列表框,但我希望對其中的項目進行排序。如何將項目列表框中如何對列表框中的項目進行升序排序

public void refreshInterface() 
{ 
    foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes) 
    { 
     var forms = new FormItems(homeForms); 
     listBox1.Items.Add(forms); 
    } 
} 

FormItems類排序:

public class FormItems 
{ 
    public DataSet1.xspGetAnalysisUsageTypesRow types { get; set; } 

    public FormItems(DataSet1.xspGetAnalysisUsageTypesRow usageTypes) 
    { 
     types = usageTypes; 
    } 

    public override string ToString() 
    { 
     return this.types.xlib_Desc; 
    } 
} 

回答

2

您可以通過直接更新列表框的源項目或項目LINQ:

list.OrderBy(x => x.Property) 

您可以在哪裏將x.Property設置爲您想要排序的屬性。這種類型將默認爲升序,這是你想要的。否則,只需要使用OrderByDescending()

+0

對LINQ,您需要使用System.Linq的補充,我經常忘記當我學習Linq時... – harsimranb

0

這是我整理LisBox品溶液的A-> Z或Z-> A:

public void Sorting(ListBox lst, String order) { 
       if (order.Equals("A-Z")) 
       { 
        if (lst.Items.Count > 1) 
        { 
         bool swapped; 
         do 
         { 
          int counter = lst.Items.Count - 1; 
          swapped = false; 

          while (counter > 0) 
          { 
           // Compare the items 
           if (lst.Items[counter].ToString().CompareTo(lst.Items[counter - 
    1].ToString()) < 0) 
           { 
            // Swap the items. 
            object temp = lst.Items[counter]; 
            lst.Items[counter] = lst.Items[counter - 1]; 
            lst.Items[counter - 1] = temp; 
            swapped = true; 
           } 
           // Decrement the counter. 
           counter -= 1; 
          } 
         } 
         while ((swapped == true)); 
        } 
       } 
       if (order.Equals("Z-A")) { 
        if (lst.Items.Count > 1) 
        { 
         bool swapped; 
         do 
         { 
          int counter = lst.Items.Count - 1; 
          swapped = false; 

          while (counter > 0) 
          { 
           // Compare the items 
           if (lst.Items[counter].ToString().CompareTo(lst.Items[counter - 
    1].ToString()) > 0) 
           { 
            // Swap the items. 
            object temp = lst.Items[counter]; 
            lst.Items[counter] = lst.Items[counter - 1]; 
            lst.Items[counter - 1] = temp; 
            swapped = true; 
           } 
           // Decrement the counter. 
           counter -= 1; 
          } 
         } 
         while ((swapped == true)); 
        } 
       } 

      } 
相關問題