我有一个基于以下内容排序的LINQ查询:
.OrderByDescending (l => l.foo == "ASDF")
.ThenByDescending (l => l.IsValid)
.ThenByDescending (l => l.Category == "X")
.ThenByDescending (l => l.Size)
.ThenByDescending (l => l.Description.Contains("Y")
.Thenby (l => l.ShelfNumber)
.Thenby (l => l.ItemNumber)
.ToList()
我确信可能有更好的方法来编写该查询,但我的问题是如何为以这种方式排序的视图编写SQL子句?
从我看到的ORDER BY子句不允许你基于任何值,只有列。
答案 0 :(得分:0)
要根据SQL语句中的值进行排序,您可以使用CASE语句,如下所示:
SELECT *
FROM [YourTable]
ORDER BY
(CASE
WHEN [foo] = 'ASDF' THEN 1
WHEN NOT ([foo] = 'ASDF') THEN 0
ELSE NULL
END) DESC
答案 1 :(得分:0)
您可以使用IComparer的实现进行更复杂的比较,例如:
项目的比较器类:
private class MyComparer : IComparer<Tuple<int, int>>
{
private readonly double extraData;
public MyComparer(double extraData)
{
// TODO: Complete member initialization
this.extraData = extraData;
}
public int Compare(Tuple<int, int> x, Tuple<int, int> y)
{
if (extraData < 10)
return x.Item1 - x.Item1;
else
return x.Item2 - x.Item2;
}
}
代码:
List<Tuple<int, int>> collection = new List<Tuple<int, int>>();
//Fill the list...
double extraData = 0.5d;
MyComparer comparer = new MyComparer(extraData);
collection.OrderByDescending(x => x, comparer);
问题是如果你想使用在以前的LINQ中创建的匿名结构,你不能这样做。