Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LINQ to move item to top of list

Tags:

c#

sorting

linq

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();
like image 533
Chris James Avatar asked Nov 03 '09 16:11

Chris James


11 Answers

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();
like image 196
Jon Skeet Avatar answered Oct 05 '22 00:10

Jon Skeet


LINQ is strong in querying collections, creating projections over existing queries or generating new queries based on existing collections. It is not meant as a tool to re-order existing collections inline. For that type of operation it's best to use the type at hande.

Assuming you have a type with a similar definition as below

class Item {
  public int Id { get; set; }
  ..
}

Then try the following

List<Item> list = GetTheList();
var index = list.FindIndex(x => x.Id == 12);
var item = list[index];
list[index] = list[0];
list[0] = item;
like image 32
JaredPar Avatar answered Oct 05 '22 01:10

JaredPar


var allCountries = repository.GetCountries();
allCountries.OrderByDescending(o => o.id == 12).ThenBy(o => o.id) 

This will insert the object with id=12 at the top of the list and rotate the rest down, preserving the order.

like image 35
Nick Gillum Avatar answered Oct 05 '22 02:10

Nick Gillum


Linq generallyworks on Enumerables, so it doesn't now that the underlying type is a collection. So for moving the item on top of the list I would suggest using something like (if you need to preserve the order)

var idx = myList.FindIndex(x => x.id == 592);
var item = myList[idx];
myList.RemoveAt(idx);
myList.Insert(0, item);

If your function returns only an IEnumerable, you can use the ToList() method to convert it to a List first

If you don't preserve the order you can simply swap the values at position 0 and position idx

like image 41
Grizzly Avatar answered Oct 05 '22 01:10

Grizzly


Here is an extension method you might want to use. It moves the element(s) that match the given predicate to the top, preserving order.

public static IEnumerable<T> MoveToTop(IEnumerable<T> list, Func<T, bool> func) {
    return list.Where(func)
               .Concat(list.Where(item => !func(item)));
}

In terms of complexity, I think it would make two passes on the collection, making it O(n), like the Insert/Remove version, but better than Jon Skeet's OrderBy suggestion.

like image 40
configurator Avatar answered Oct 05 '22 02:10

configurator


You can "group by" in two groups with Boolean key, and then sort them

var finalList= allCountries
                .GroupBy(x => x.id != 592)
                .OrderBy(g => g.Key)
                .SelectMany(g => g.OrderBy(x=> x.id ));
like image 30
Filip Avatar answered Oct 05 '22 01:10

Filip


I know this a old question but I did it like this

class Program
{
    static void Main(string[] args)
    {
        var numbers = new int[] { 5, 10, 12, 1 };

        var ordered = numbers.OrderBy(num => num != 10 ? num : -1);

        foreach (var num in ordered)
        {
            Console.WriteLine("number is {0}", num);
        }

        Console.ReadLine();
    }
}

this prints:

number is 10
number is 1
number is 5
number is 12

like image 34
Gaotter Avatar answered Oct 05 '22 02:10

Gaotter


public static IEnumerable<T> ServeFirst<T>(this IEnumerable<T> source, 
    Predicate<T> p)
{
    var list = new List<T>();

    foreach (var s in source)
    {
        if (p(s))
            yield return s;
        else
            list.Add(s);
    }

    foreach (var s in list)
        yield return s;
}
like image 27
Grozz Avatar answered Oct 05 '22 00:10

Grozz


Its interesting the number of approaches you find when trying to solve a problem.

var service = AutogateProcessorService.GetInstance();
var allConfigs = service.GetAll();
allConfigs = allConfigs.OrderBy(c => c.ThreadDescription).ToList();
var systemQueue = allConfigs.First(c => c.AcquirerId == 0);
allConfigs.Remove(systemQueue);
allConfigs.Insert(0, systemQueue);
like image 34
Adeola Ojo Gabriel Avatar answered Oct 05 '22 02:10

Adeola Ojo Gabriel


To also check if the item was found without Exception, something like:

var allCountries = repository.GetCountries();
var lookup = allCountries.ToLookup(x => x.id == 592);  
var finalList = lookup[true].Concat(lookup[false]).ToList();
if ( lookup[true].Count() != 1 ) YouAreInTrouble();
like image 41
Slai Avatar answered Oct 05 '22 01:10

Slai


Even easier if you have the object:

listOfObjects.Remove(object);
listOfObjects.Insert(0, object);
like image 32
HWTurk Avatar answered Oct 05 '22 01:10

HWTurk