【问题标题】:linq query to sort and then bring a particular group of records to toplinq 查询进行排序,然后将一组特定的记录置于顶部
【发布时间】:2014-09-04 02:02:39
【问题描述】:

我正在尝试使用 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

【问题讨论】:

标签: linq


【解决方案1】:

一种选择是创建一个可在您的 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));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多