按自定义订单订购商品
Order items by custom order
我在数据库中插入了一个列表:
List<House> houses = new List<House> {
new House { Id = 1, Type = "A" },
new House { Id = 2, Type = "B" },
new House { Id = 3, Type = "C" }
new House { Id = 4, Type = "B" }
}
使用 Linq to Entities 我需要按类型订购房屋,但它应该是:
Houses of Type C
Houses of Type A
Houses of Type B
如何操作?
您可以像这样链接 ? :
运算符来创建自定义排序:
var query = from h in context.Houses
orderby h.Type == "C" ? 0 : (h.Type == "A" ? 1 : 2)
select h;
或方法语法
var query = context.Houses.OrderBy(h => h.Type == "C" ? 0 : (h.Type == "A" ? 1 : 2))
抱歉回答晚了,但我会写一个类似这样的扩展:
static void Main(string[] args)
{
var items = new[] { 1, 2, 3, 4, 5 }.AsQueryable();
//for example, revert entire list
var newOrder = new Dictionary<int, int>() { { 1, 5 }, { 2, 4 }, { 3, 3 }, { 4, 2 }, { 5, 1 } };
var sorted = items.OrderBy(newOrder.ToSwithExpression())).ToList();
foreach(var i in sorted)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
static Expression<Func<T, K>> ToSwithExpression<T, K>(this Dictionary<T, K> dict, K defaultValue = default(K))
{
var paramm = Expression.Parameter(typeof(T), "x");
//If nothing maps - use default value.
Expression iter = Expression.Constant(defaultValue);
foreach (var kv in dict)
{
iter = Expression.Condition(Expression.Equal(paramm, Expression.Constant(kv.Key)), Expression.Constant(kv.Value, typeof(K)), iter);
}
return Expression.Lambda<Func<T, K>>(Expression.Convert(iter, typeof(K)), paramm);
}
如您所见,您可以指定映射开关而不是字典。我使用字典只是因为它更容易。 EF把这个嚼烂改成类似其他答案的表达式是没有问题的
我在数据库中插入了一个列表:
List<House> houses = new List<House> {
new House { Id = 1, Type = "A" },
new House { Id = 2, Type = "B" },
new House { Id = 3, Type = "C" }
new House { Id = 4, Type = "B" }
}
使用 Linq to Entities 我需要按类型订购房屋,但它应该是:
Houses of Type C
Houses of Type A
Houses of Type B
如何操作?
您可以像这样链接 ? :
运算符来创建自定义排序:
var query = from h in context.Houses
orderby h.Type == "C" ? 0 : (h.Type == "A" ? 1 : 2)
select h;
或方法语法
var query = context.Houses.OrderBy(h => h.Type == "C" ? 0 : (h.Type == "A" ? 1 : 2))
抱歉回答晚了,但我会写一个类似这样的扩展:
static void Main(string[] args)
{
var items = new[] { 1, 2, 3, 4, 5 }.AsQueryable();
//for example, revert entire list
var newOrder = new Dictionary<int, int>() { { 1, 5 }, { 2, 4 }, { 3, 3 }, { 4, 2 }, { 5, 1 } };
var sorted = items.OrderBy(newOrder.ToSwithExpression())).ToList();
foreach(var i in sorted)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
static Expression<Func<T, K>> ToSwithExpression<T, K>(this Dictionary<T, K> dict, K defaultValue = default(K))
{
var paramm = Expression.Parameter(typeof(T), "x");
//If nothing maps - use default value.
Expression iter = Expression.Constant(defaultValue);
foreach (var kv in dict)
{
iter = Expression.Condition(Expression.Equal(paramm, Expression.Constant(kv.Key)), Expression.Constant(kv.Value, typeof(K)), iter);
}
return Expression.Lambda<Func<T, K>>(Expression.Convert(iter, typeof(K)), paramm);
}
如您所见,您可以指定映射开关而不是字典。我使用字典只是因为它更容易。 EF把这个嚼烂改成类似其他答案的表达式是没有问题的