1

我有一个字符串列表让我们说

List<string> mia = new list<string>;

我正在从数据库中向其中添加数据

using (SqlCommand command = new SqlCommand("SELECT xyz FROM table",sqlConnection1))
{
     sqlConnection1.Open();
     using (SqlDataReader reader = command.ExecuteReader())
     {
          while (reader.Read())
          {
               mia.Add(reader["xyz"].ToString());
          }

     }
     sqlConnection1.Close();                     
}

数据已成功添加到其中。

combobox.ItemsSource =mia;

即使这样也很好

但是当我尝试做

comboOpthol.ItemsSource =mia.Sort();

智能感知抛出错误无法将类型“void”隐式转换为System.collections.IEnumerable. 为什么会出现这个错误。我的列表包含所有数据,那么为什么显示它无效?列表定义列表的方式有问题吗?

4

4 回答 4

8

因为该Sort()方法没有返回值(它将列表排序并返回void)。您需要先排序,然后将列表分配给项目源:

mia.Sort();
comboOpthol.ItemsSource = mia;
于 2013-01-19T13:18:09.880 回答
2

List<T>.Sort不返回新列表,而是对现有列表进行排序。

mia.Sort();
comboOpthol.ItemsSource = mia;

考虑在数据库级别使用 对结果进行排序ORDER BY

You've tagged your question with linq which leads me to believe you think List<T>.Sort() is linq. It is not, it's a method of List<T>.

于 2013-01-19T13:18:30.460 回答
1

You should sort it before setting it as source:

mia.Sort();
comboOpthol.ItemsSource =mia;
于 2013-01-19T13:18:48.223 回答
1

This is happening because .Sort() does not return a "new" sorted list. It just sorts the excisting one.

Just do

mia.Sort();
comboOpthol.ItemsSource = mia;
于 2013-01-19T13:19:08.963 回答