Use LINQ to move item to top of list

qui picture qui · Nov 3, 2009 · Viewed 69.1k times · Source

Is there a way to move an item of say id=10 as the first item in a list using LINQ?

Item A - id =5
Item B - id = 10
Item C - id =12
Item D - id =1

In this case how can I elegantly move Item C to the top of my List<T> collection?

This is the best I have right now:

var allCountries = repository.GetCountries();
var topitem = allCountries.Single(x => x.id == 592);  
var finalList = new List<Country>();
finalList.Add(topitem);
finalList = finalList.Concat(allCountries.Where(x=> x.id != 592)).ToList();

Answer

Jon Skeet picture Jon Skeet · Nov 3, 2009

What do you want to order by, other than the known top item? If you don't care, you can do this:

var query = allCountries.OrderBy(x => x.id != 592).ToList();

Basically, "false" comes before "true"...

Admittedly I don't know what this does in LINQ to SQL etc. You may need to stop it from doing the ordering in the database:

var query = allCountries.AsEnumerable()
                        .OrderBy(x => x.id != 592)
                        .ToList();