Craig
Craig

Reputation: 18694

Linq, force an item to be first?

I have a List<> of MyPersonObjects. The list is a list of people who I can assign something to. In this list, I include myself (As the task can be assigned to me - and usually is).

So, I want to make sure myself is at the top of the list. I know my personId, which is a property of my person object - so is there a way to order the list to make sure I am first, and then the rest, alphabetically by surname (which is another property of my object)

Upvotes: 1

Views: 505

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

You can just order the list by two separate criteria, the OrderBy will be the main sort order, if the values are equal (1 for all except you), ThenBy is used.

personList.OrderBy(x => x.Id == myId ? 0 : 1)
           .ThenBy(x => x.Surname);

Upvotes: 6

nemesv
nemesv

Reputation: 139768

One way is to sort the list by surname with Linq and then remove yourself and put back at the first place:

var personList = db.MyPersonObjects.OrderBy(p => p.Surname).ToList();
var myself = personList.Single(p => p.Id == myselfId);
personList.Remove(myself);
personList.Insert(0, myself);

Or create a custom comparer IComparer<MyPersonObject> where the implementation is something like:

public class PersonCompaper : IComparer<MyPersonObject>
{
    private readonly int personId;

    public PersonCompaper(int personId)
    {
        this.personId = personId;
    }

    public int Compare(MyPersonObject x, MyPersonObject y)
    {
        if (x.Id == personId && y.Id == personId)
           return 0;
        if (x.Id == personId)
            return 1;
        if (y.Id == personId)
            return -1;            
        return string.Compare(x.Surname, y.Surname);
    }
}

Then you use it in the OrderBy

db.MyPersonObjects.OrderBy(p => p, new PersonCompaper(myselfId))

Upvotes: 3

Related Questions