Reordering a single item from query results

I am looking for an elegant solution to the order problem that I have.

I have a database query that returns a list of results sorted by name. The results will always contain one element called the "Primary Element", which should always appear first in the list of results. This item is not marked with a separate field in the database and therefore needs to be identified by name.

For example, if the results are as follows:

"A Item"
"B Item"
"Main Item"
"Y Item"
"Z Item"

I need the alphabetic appearance to remain, but with the exception that the "Primary Element" first appears:

"Main Item"
"A Item"
"B Item"
"Y Item"
"Z Item"

, , pl/sql, , - .Net, IEnumerable, .

+3
3

:

query
  .OrderBy(item => item.Title) // alphabetical
  .OrderByDescending(item => item.Title == "Main Item"); // put Main Item first, bool==true

, 2- OrderBy

query.OrderByDescending(item => item.Title == "Main Item");
+3

:

SELECT * 
FROM MyTable 
ORDER BY 
        CASE 
            WHEN Name = 'Main Item' THEN ' ' 
            ELSE Name 
        END
0

I like the payo answer, but since it is repeated throughout the collection for the second time instead of the simple logic of moving the element, I consider it appropriate to post this answer as well:

List<MyClass> items = GetItemsFromDB();

int i = items.FindIndex(x => x.Name == "Main Item");

MyClass mainItem = items[i];
items.RemoveAt(i);
items.Insert(0, mainItem);
0
source

All Articles