subash
subash

Reputation: 4137

linq query to sort and then bring a particular group of records to top

i am trying a linq query to sort a group of elements and then bring a elements that satisfy particular condition to top.

for eg, if i have list of elements like below:

ID   Names
1    Angie
2    Bret
3    Salva
4    cunnighma
5    maria
6    Galvin
7    Newton 
8    Desmond   

and if i pass condition as Name=Galvin then the resultset should be sorted first and then bring the value inn condition to top.The resultset would like below

   ID    Names
    6    Galvin
    1    Angie
    2    Bret
    4    cunnighma
    8    Desmond
    5    maria
    7    Newton 
    3    Salva

Upvotes: 0

Views: 230

Answers (1)

Carlo Bos
Carlo Bos

Reputation: 3293

One option is to create an extension method that can be used in your linq expression. The following solution does just that. I've made it work for the case of multiple matches as well.

The example code below will have the following output:

6:Galvin
1:Angie
2:Bret
4:cunnighma
8:Desmond
5:maria
7:Newton
3:Salva

Here's the code:

void Main()
{
    // Setup the example data
    var names = new List<Record>
    {
        new Record { Id = 1, Name = "Angie" },
        new Record { Id = 2, Name = "Bret" },
        new Record { Id = 3, Name = "Salva" },
        new Record { Id = 4, Name = "cunnighma" },
        new Record { Id = 5, Name = "maria" },
        new Record { Id = 6, Name = "Galvin" },
        new Record { Id = 7, Name = "Newton" },
        new Record { Id = 8, Name = "Desmond" }
    };
    
    // Sort the list and move the matches to the top
    var result = names
       .OrderBy(x => x.Name)
       .MoveToTop(x => x.Name.Contains("alvin"));

    // Display the results to the console
    result
       .ToList()
       .ForEach(x => Console.WriteLine($"{x.Id}:{x.Name}"));
}


public class Record
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> MoveToTop<T>(this IEnumerable<T> list,  Func<T, bool> predicate)
    {
        var matches = list.Where(predicate);            
        return matches.Concat(list.Except(matches));
    }
}

Upvotes: 2

Related Questions