Search code examples
c#.netlinq

Sort Object Collection by specific string C# LINQ


I am calling an employee search API provided by a third party which returns me a list of employees as a search result. This Employee class has n number of properties (for example, FirstName, LastName, Address, Mobile No and many others). I want to compare the "FirstName" property of these search results with the search text. If it matches, I want these matching results sorted at the top of the collection. So far, I have tried using IComparer and IComparable but they both are not suitable for my requirement. Sharing an example of my requirement below :

Example: I searched for "John" in API and API gave me 10 results. Out of these 10 results, only 1 had john as a first name, and the rest 9 of them have john in other properties. I want an employee with FirstName "John" as the first result.


Solution

  • You can sort your list via

    var sorted = resultFromApi.OrderByDescending(x => x.FirstName == "John").ToList();
    

    Your new list will have all items where FirstName is "John" in the beginning, and all items where FirstName has another value in the end.