Skip to main content
 首页 » 编程设计

c#之OrderBy 不工作

2024年02月06日12dflying

我正在尝试以下代码:

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();