How can I use linq to sort by multiple fields?

前端 未结 6 1518
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 05:21

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)
         


        
6条回答
  •  清酒与你
    2020-12-29 05:50

    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 query = from item in items select item;
    if (sortExpressionsExist)
    {
        // Won't be read in the first iteration; will be written to
        IOrderedEnumerable 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 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;
    }
    

提交回复
热议问题