c# - OrderBy 不工​​作

标签 c# linq morelinq

我正在尝试以下代码:

public IList<Brand> GetMobileDeviceBrands()
{
     var dataContext = dataContextFactory.CreateContext();

     var brands = (from b in dataContext.Brands
                   join d in dataContext.Devices on b.ID equals d.BrandID
                   where d.DeviceTypeID != 1
                   select b).OrderBy(b => b.Name).Distinct().ToList();

     return brands;         // not ordered by Name here
}

但没有得到预期的结果。

如果我在 Controller 中将 orderBy 写成:

var Brands = devicesListService.GetMobileDeviceBrands().OrderBy(b => b.Name).ToList();

它做得很好。我不知道出了什么问题。

最佳答案

distinct 运算符不保证保持值的顺序不变,因此您需要交换 orderby 和 distinct 运算符:

var brands = (from b in dataContext.Brands
                   join d in dataContext.Devices on b.ID equals d.BrandID
                   where d.DeviceTypeID != 1
                   select b).Distinct().OrderBy(b => b.Name).ToList();

关于c# - OrderBy 不工​​作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26401434/

相关文章:

c# - 将 XhtmlTextWriter 与 XmlTextReader 结合使用

c# - 使用 C# 将文件写入 Linux 中的网络位置

c# - 从位图图像列表创建 .avi 文件

c# - RelayCommand 的常见实现是否违反了 MVVM 模式?

c# - 只有一个匹配属性的 MoreLinq ExceptBy

c# - 如何解决 Enumerable 和 MoreLINQ 之间不明确的 ZIP 调用?

c# - 为什么 i.Parent.ReplaceWith(i) 不抛出异常?

c# - 通过 POST、PUT 方法返回 400 Bad Request,但 GET 工作正常

c# - 将 Dictionary<string, Task<string>> 转换为 Dictionary<string, string>

c# - 从两个表中获取不同记录的 Linq 查询