如何按自定义顺序订购实体列表?
How to order a list of entities by a custom order?
我有一个可以这样表示的实体列表:
Type | Property A | Property B | ...
--------------------------------------
A | ABC | 123 | ...
A | ABC | 123 | ...
D | ABC | 123 | ...
D | ABC | 123 | ...
B | ABC | 123 | ...
C | ABC | 123 | ...
Type 是一个字符串,只能是 4 个不同值之一(例如 A、B、C、D)
我需要按 Type 对这些实体进行排序,但要使用自定义顺序(例如 A、D、B、C)。
我试过这样的事情:
var orderType = new Dictionary<string, int>() {
{ "A", 0 },
{ "D", 1 },
{ "B", 2 },
{ "C", 3 }
};
return db.MyEntity
.OrderBy(x => orderType[x.Type])
.ToList();
但是我得到以下错误:
LINQ to Entities 无法识别方法 'Int32 get_Item(System.String)' 方法,并且此方法无法转换为存储表达式。
我不明白这个错误,也不知道如何处理这个 OrderBy。您能否告诉我如何使用自定义订单按 类型 订购这些实体?
I don't understand this error
这是因为 LINQ TO SQL 无法将 Dictionary 的 Int32 get_Item(System.String)
翻译成 SQL 中的等效操作。
解决它的一个非常简单的方法是通过 AsEnumerable()
将实体放入内存中:
return db.MyEntity.AsEnumerable().
.OrderBy(x => orderType[x.Type])
.ToList();
我有一个可以这样表示的实体列表:
Type | Property A | Property B | ...
--------------------------------------
A | ABC | 123 | ...
A | ABC | 123 | ...
D | ABC | 123 | ...
D | ABC | 123 | ...
B | ABC | 123 | ...
C | ABC | 123 | ...
Type 是一个字符串,只能是 4 个不同值之一(例如 A、B、C、D) 我需要按 Type 对这些实体进行排序,但要使用自定义顺序(例如 A、D、B、C)。
我试过这样的事情:
var orderType = new Dictionary<string, int>() {
{ "A", 0 },
{ "D", 1 },
{ "B", 2 },
{ "C", 3 }
};
return db.MyEntity
.OrderBy(x => orderType[x.Type])
.ToList();
但是我得到以下错误:
LINQ to Entities 无法识别方法 'Int32 get_Item(System.String)' 方法,并且此方法无法转换为存储表达式。
我不明白这个错误,也不知道如何处理这个 OrderBy。您能否告诉我如何使用自定义订单按 类型 订购这些实体?
I don't understand this error
这是因为 LINQ TO SQL 无法将 Dictionary 的 Int32 get_Item(System.String)
翻译成 SQL 中的等效操作。
解决它的一个非常简单的方法是通过 AsEnumerable()
将实体放入内存中:
return db.MyEntity.AsEnumerable().
.OrderBy(x => orderType[x.Type])
.ToList();