How to order a list of objects for an individual order?

I have a list of objects that can be represented as follows:

Type | Property A | Property B | ... -------------------------------------- A | ABC | 123 | ... A | ABC | 123 | ... D | ABC | 123 | ... D | ABC | 123 | ... B | ABC | 123 | ... C | ABC | 123 | ... 

A type is a string and can only be one of 4 different values ​​(for example, g A, B, C, D) I need to arrange these objects using Type , but with a custom order (for example, A, D, B, C).

I tried something like this:

 var orderType = new Dictionary<string, int>() { { "A", 0 }, { "D", 1 }, { "B", 2 }, { "C", 3 } }; return db.MyEntity .OrderBy(x => orderType[x.Type]) .ToList(); 

But I get the following error:

LINQ to Entities does not recognize the 'Int32 get_Item (System.String)' method, and this method cannot be translated into a storage expression.

I do not understand this error and do not know what to do with this OrderBy. Could you tell me how to arrange these objects using Type with a custom order?

+6
source share
1 answer

I do not understand this error

This is because LINQ TO SQL cannot translate the Int32 get_Item(System.String) dictionary into an equivalent operation in SQL.


The easiest way to solve this problem is to transfer entities to memory using AsEnumerable() :

 return db.MyEntity.AsEnumerable(). .OrderBy(x => orderType[x.Type]) .ToList(); 
+4
source

Source: https://habr.com/ru/post/984644/


All Articles