Maintaining an order when selecting a static group from a table

Let's say I have a list of static lists of identifiers in a specific order:

List<int> ordered = new List<int> {7,2,3,4,5};

And I would like to select items from a database supporting this order.

Trivial:

 var posts = ( from p in Current.DB.Posts
                        where ordered.Contains(p.Id)
                        select p).ToList();

It returns quickly, but does not work.

How to select these messages from db and maintain order in an elegant and efficient way?

+3
source share
4 answers

This combines Marc's answer and your answer:

var dict = Current.DB.Posts.Where(p => ordered.Contains(p.Id))
           .ToDictionary(p => p.Id);
return ordered.Select(id => dict[id]).ToList();

As he steps down OrderBy, I suspect he will be a little more efficient. This, of course, is a bit prettier.

+1
source

order-by, - - , , , IIRC ( , parallelism, )

; , . , :

var dict = Current.DB.Posts.Where(p => ordered.Contains(p.Id))
                  .ToDictionary(p => p.Id);

, , .

+3

:

        var reverseIndex = ordered.Select((id, index) => new { Id = id, Index = index }).ToDictionary(pair => pair.Id, s => s.Index);

        model.Posts = Current.DB.Posts
            .Where(p => postIds.Contains(p.Id))
            .AsEnumerable()
            .OrderBy(p => reverseIndex[p.Id] )
            .ToList();

, .

+1

List<int> .

var posts = ( from p in Current.DB.Posts 
                        where ordered.Contains(p.Id) 
                        select p).ToList(); 

return ordered.Select(o => posts.Single(post => post.Id == o)).ToList();

, select

ordered.Select(o => Current.DB.Posts.Single(post => post.Id == o)).ToList();
0

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


All Articles