Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Linq to move item to bottom of list

Tags:

c#

asp.net

linq

This is my code:

var list = from c in child_categories orderby c.Translated_Syntax 
           select new { Name = c.Translated_Syntax, ID = c.ID_Category } ;

lst_category.DataSource = list;    
lst_category.DataBind();

My list of categories is: Car, Other, Children, House, Girl, Show.

If I order my list, the result it will be:

  • Car
  • Children
  • Girl
  • Other
  • Show

But I want the 'Other' item to be placed to bottom of list. Something like this:

  • Car
  • Children
  • Girl
  • Show
  • Other

How can I do this?

like image 654
POIR Avatar asked Jan 16 '14 13:01

POIR


1 Answers

You can use this Orderby-"trick":

from c in child_categories 
orderby c.Translated_Syntax == "Other", c.Translated_Syntax

You can remember how it works in this way: the comparison returns a bool where true is 1 and false is 0. That's why orderby Translated_Syntax == "Other" will list the "Others" last. If you want it to precede you either have to reverse the condition or (better) use descending instead.

like image 106
Tim Schmelter Avatar answered Nov 19 '22 15:11

Tim Schmelter