【发布时间】:2021-01-14 15:36:01
【问题描述】:
我想通过 SQL 查询对表中的 var 'StorageLocation' 进行排序,并按定义的数组对其进行排序。
我的数组:string[] sortedLocations = {"Location A", "Location B", "Location 2"};
我尝试了什么:reportRecords.OrderBy(o => o.StorageLocation == sortedLocations[o])
此代码当前具有所需的结果。它将按我首先设置的 StorageLocations 进行排序,然后将其余部分附加到末尾。当我更改/重新排序 StorageLocation 时,这有点乏味。
public void ActiveReport_ReportStart()
{
// Create report query and set the report datasource
using (var context = sqlDB.CreateContext())
{
var reportRecords = (from ii in context.IssuedItems
where (ii.Item.BarcodeId.Length == 9)
select new
{
ii.Item.StorageLocation,
ii.Item.BarcodeId,
ii.User.UsernameId
}).ToList();
reportRecords = reportRecords.OrderBy(o =>
// Order by defined StorageLocation first
o.StorageLocation == "Location A" ? 1 :
o.StorageLocation == "Location B" ? 2 :
o.StorageLocation == "Location 2" ? 3 : 4
).ThenBy(o => o.BarcodeId).ToList();
rpt.DataSource = reportRecords;
}
}
非常感谢任何帮助! :)
这样会更有效吗?
List<reportRecords> definedLocations = new List<reportRecords>()
{
"Location A",
"Location B",
"Location 2"
};
List<reportRecords> sorted = (from e in definedLocations
orderby e.BarcodeId
select e).ToList();
【问题讨论】:
-
您可以将其设为
Dictionary<string, int> { [1] = "Location A", [2] = ...},然后将其设为OrderBy(o => sortedLocations.GetValueOrDefault(o.StorageLocation, 4)) -
@juharr 谢谢你的回复。我试图摆脱数组中的索引号,只是根据第一个元素对其进行排序。我在 SQL 数据库中有很多位置,我可能需要修改数组以在“位置 A”之前出现不同的位置,所以我想轻松地将其添加到顶部。我编辑了这篇文章,希望有一个更清晰的例子。