linq查询排序,然后将一组特定记录置于顶部

时间:2014-07-14 07:41:01

标签: linq

我正在尝试使用linq查询对一组元素进行排序,然后将满足特定条件的元素置于顶部。

例如,如果我有以下元素列表:

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

如果我将条件作为Name = Galvin传递,则应首先对结果集进行排序,然后将值inn条件置于顶部。结果集如下所示

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

1 个答案:

答案 0 :(得分:0)

一个选项是创建可在linq表达式中使用的扩展方法。以下解决方案可以做到这一点。我也使其适用于多个比赛。

下面的示例代码将具有以下输出:

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

这是代码:

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));
    }
}