通过自定义订单订购商品

问题描述 投票:1回答:2

我有一个插入数据库的列表:

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进行实体,我需要按类型订购房屋,但应该是:

 Houses of Type C
 Houses of Type A
 Houses of Type B

如何执行?

c# entity-framework-core linq-to-entities entity-framework-core-3.1
2个回答
1
投票

您可以链接? :运算符以创建这样的自定义排序:

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

0
投票

对不起,我迟到了,但是我会写一个类似这样的扩展名:

    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在咀嚼这个单词并将其转换成与其他答案表达类似的单词时没有问题。

© www.soinside.com 2019 - 2024. All rights reserved.