João Paiva João Paiva - 2 months ago 5
ASP.NET (C#) Question

How can I push an existing item to the end of a list?

I have a list of Teams. A team is defined in this way:

public class Team
public int ID { get; set; }

public string Name { get; set; }

After I query the database with
, which returns a
, I need to push one of the teams of that list with the name "Total" to the end of the list. How can I achieve this?


First, you can do that directly in the query:

var list = db.Teams.OrderBy(t => t.Name == "Total" ? 1 : 0).ToList();

But if you insist doing it after the list is populated, then you can use the FindIndex method to find the index of the total item (if any) and them move the item to the end using RemoveAt and Add methods:

var list = db.Teams.ToList();
int index = list.FindIndex(t => t.Name == "Total");
if (index >= 0 && index != list.Count - 1)
    var total = list[index];

In the later case, if you don't really care about the order of the other items in the list, another more efficient way would be to simply exchange the total with the last element:

if (index >= 0 && index != list.Count - 1)
    var total = list[index];
    list[index] = list[list.Count - 1];
    list[list.Count - 1] = total;