如何在Linq查询中包含OrderBy

时间:2014-09-10 07:34:23

标签: c# sql-server linq radcombobox

我想在SelectionName上应用OrderBy Ascending,通过对radcombobox中的项进行排序

dropDown.Items.AddRange(items.Select(x => new RadComboBoxItem(x.SelectionName, x.SelectionValue)).ToArray());

3 个答案:

答案 0 :(得分:3)

dropDown.Items.AddRange(items
  .OrderBy(x => x.SelectionName)
  .Select(x => new RadComboBoxItem(x.SelectionName, x.SelectionValue))
  .ToArray());

如您所评论,您希望按其他值排序,可以使用.ThenBy(x => x.Value)

在你的情况下;

dropDown.Items.AddRange(items
  .OrderBy(x => x.SelectionName)
  .ThenBy(x => x.SortOrder)
  .Select(x => new RadComboBoxItem(x.SelectionName, x.SelectionValue))
  .ToArray());

答案 1 :(得分:0)

您可以在将项目添加到组合框之前对其进行排序:

dropDown.Items.AddRange(items
    .OrderBy(x=>x.SelectionName)
    .Select(x=>new RadComboBoxItem(x.SelectionName,x.SelectionValue)
    .ToArray());

您的probalby不需要致电ToArray(),因为AddRange可能与IEnumerable一起使用。我没有检查所有 RadComboBox类,但至少AJAX version适用于IEnumerable。

更好的选择是在您的平台(ASP.NET,WPF,Windows Forms?)中使用绑定支持将您的组合绑定到有序的可枚举项,而不是构造原始组合框项。

<强>更新

要按多个字段排序,请使用包含所需字段的匿名类型,例如:

dropDown.Items.AddRange(items
    .OrderBy(x=>new {x.SortOrder,x.SelectionName})
    ...

OrderBy的参数是一个lambda 函数,用于创建订单键。

指定x=>x.SelectionName时,您指定的函数接收项x并返回SelectionName属性的内容作为键。

当您键入x=>new {x.SortOrder,x.SelectionName}时,指定一个函数,该函数返回一个匿名类型,其字段由SortOrderSelectionName参数填充。

在这种情况下,使用LINQ语法而不是LINQ方法更清楚。相同的代码可以写成:

var orderedItems=from item in items
                 orderby item.SortOrder,item.SelectionName
                 select new RadComboBoxItem(item.SelectionName,item.SelectionValue);
dropDown.Items.AddRange(orderedItems);

答案 2 :(得分:0)

这会有所帮助:

dropDown.Items.AddRange(items
  .Select(x => new RadComboBoxItem(x.SelectionName, x.SelectionValue))
  .OrderBy(x => x.SelectionName)
  .ToArray());