如何使用linq按多个字段排序? [英] How can I use linq to sort by multiple fields?

查看:90
本文介绍了如何使用linq按多个字段排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个模拟数据源,希望能够在该数据源上传递SortExpressions列表.

I'm creating a mock data source that I want to be able to pass in a list of SortExpressions on.

public SortExpression(string name, SortDirection direction)
{
     this.name = name;
     this.direction = direction;
}

更新,其中包含Jon Skeet的代码以及整个类. GetData()只是用x条记录填充对象.

Update with Jon Skeet's code and also the entire class. GetData() is just populating the object with x number of records.

public class Data
{

public int Id { get; set; }
public Guid gId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public DateTime Created { get; set; }
public string SortMe { get; set; }
public static List<Data> GetFakeData(int start, int numberToFetch, IList<SortExpression> sortExpressions, IList<FilterExpression> filterExpressions, out int totalRecords)
{
    DataCollection items = GetData();
    IEnumerable<Data> query = from item in items select item;

    bool sortExpressionsExist = sortExpressions != null;
    if (sortExpressionsExist)
    {
        // Won't be read in the first iteration; will be written to
        IOrderedEnumerable<Data> orderedQuery = null;
        for (int i = 0; i < sortExpressions.Count; i++)
        {
            // Avoid single variable being captured: capture one per iteration.
            // Evil bug which would be really hard to find :)
            int copyOfI = i;
            // Tailor "object" depending on what GetProperty returns.
            Func<Data, object> expression = item =>
                  item.GetType().GetProperty(sortExpressions[copyOfI].Name);

            if (sortExpressions[i].Direction == SortDirection.Ascending)
            {
                orderedQuery = (i == 0) ? query.OrderBy(expression)
                                        : orderedQuery.ThenBy(expression);
            }
            else
            {
                orderedQuery = (i == 0) ? query.OrderByDescending(expression)
                                        : orderedQuery.ThenByDescending(expression);
            }
        }
        query = orderedQuery;
    }

    bool filterExpressionsExist = filterExpressions != null;
    if (filterExpressionsExist)
    {
        foreach (var filterExpression in filterExpressions)
        {
            query.Where(item => item.GetType().GetProperty(filterExpression.ColumnName).GetValue(item, null).ToString().Contains(filterExpression.Text));
        }
    }
    totalRecords = query.Count();


       return query.Skip(start).Take(numberToFetch).ToList<Data>();
    }
}

似乎什么也没做.编译,没有错误,只是没有排序.有什么想法吗?

Doesn't seem to be doing anything. Compiles, no errors, just no sort. Any ideas?

推荐答案

有两个问题.第一个是其他人提到的-您需要使用OrderBy等返回的值.第二个是每次调用OrderBy时,都会添加一个新的主"顺序.第一次订购后,您真的想要ThenBy.不幸的是,这使它变得非常丑陋.重构后仍然很丑陋,但还不错...

There are two problems. The first is the one others have alluded to - you need to use the value returned by OrderBy etc. The second is that each time you call OrderBy, that's adding a new "primary" ordering. You really want ThenBy after the first ordering has been applied. That makes it pretty ugly, unfortunately. It's still pretty ugly after a refactoring, but not too bad...

IEnumerable<Data> query = from item in items select item;
if (sortExpressionsExist)
{
    // Won't be read in the first iteration; will be written to
    IOrderedEnumerable<Data> orderedQuery = null;
    for (int i = 0; i < sortExpressions.Count; i++)
    {
        // Avoid single variable being captured: capture one per iteration.
        // Evil bug which would be really hard to find :)
        int copyOfI = i;
        // Tailor "object" depending on what GetProperty returns.
        Func<Data, object> expression = item => 
              item.GetType()
                  .GetProperty(sortExpressions[copyOfI].Name)
                  .GetValue(item, null);

        if (sortExpressions[i].Direction == SortDirection.Ascending)
        {
            orderedQuery = (i == 0) ? query.OrderBy(expression)
                                    : orderedQuery.ThenBy(expression);
        }
        else
        {
            orderedQuery = (i == 0) ? query.OrderByDescending(expression)
                                    : orderedQuery.ThenByDescending(expression);
        }
    }
    query = orderedQuery;
}

这篇关于如何使用linq按多个字段排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆