289

文字列に「プロパティで並べ替え」という名前があります。オブジェクトのリストを並べ替えるには、Lambda/Linqを使用する必要があります。

元:

public class Employee
{
  public string FirstName {set; get;}
  public string LastName {set; get;}
  public DateTime DOB {set; get;}
}


public void Sort(ref List<Employee> list, string sortBy, string sortDirection)
{
  //Example data:
  //sortBy = "FirstName"
  //sortDirection = "ASC" or "DESC"

  if (sortBy == "FirstName")
  {
    list = list.OrderBy(x => x.FirstName).toList();    
  }

}
  1. 一連のifを使用してフィールド名(sortBy)をチェックする代わりに、ソートを行うためのよりクリーンな方法がありますか?
  2. sortはデータ型を認識していますか?
4

12 に答える 12

390

これは次のように行うことができます

list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );

.NET Frameworkは、ラムダ(emp1,emp2)=>intComparer<Employee>.

これには、強く型付けされるという利点があります。

降順/逆順が必要な場合は、パラメーターを逆にします。

list.Sort( (emp1,emp2)=>emp2.FirstName.CompareTo(emp1.FirstName) );
于 2013-01-02T16:32:28.370 に答える
75

できることの 1 つは、ラムダをより有効に使用できるように変更Sortすることです。

public enum SortDirection { Ascending, Descending }
public void Sort<TKey>(ref List<Employee> list,
                       Func<Employee, TKey> sorter, SortDirection direction)
{
  if (direction == SortDirection.Ascending)
    list = list.OrderBy(sorter);
  else
    list = list.OrderByDescending(sorter);
}

メソッドを呼び出すときに、ソートするフィールドを指定できるようになりましたSort

Sort(ref employees, e => e.DOB, SortDirection.Descending);
于 2009-04-06T19:47:01.210 に答える
56

Reflection を使用して、プロパティの値を取得できます。

list = list.OrderBy( x => TypeHelper.GetPropertyValue( x, sortBy ) )
           .ToList();

TypeHelper には次のような静的メソッドがあります。

public static class TypeHelper
{
    public static object GetPropertyValue( object obj, string name )
    {
        return obj == null ? null : obj.GetType()
                                       .GetProperty( name )
                                       .GetValue( obj, null );
    }
}

VS2008サンプル ライブラリの Dynamic LINQ も参照してください。IEnumerable 拡張機能を使用して List を IQueryable としてキャストし、ダイナミック リンク OrderBy 拡張機能を使用できます。

 list = list.AsQueryable().OrderBy( sortBy + " " + sortDirection );
于 2009-04-06T19:46:04.787 に答える
21

これが私の問題を解決した方法です:

List<User> list = GetAllUsers();  //Private Method

if (!sortAscending)
{
    list = list
           .OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}
else
{
    list = list
           .OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}
于 2012-02-20T13:13:52.227 に答える
16

式による順序の構築は、ここで読むことができます

リンクのページから恥知らずに盗まれた:

// First we define the parameter that we are going to use
// in our OrderBy clause. This is the same as "(person =>"
// in the example above.
var param = Expression.Parameter(typeof(Person), "person");

// Now we'll make our lambda function that returns the
// "DateOfBirth" property by it's name.
var mySortExpression = Expression.Lambda<Func<Person, object>>(Expression.Property(param, "DateOfBirth"), param);

// Now I can sort my people list.
Person[] sortedPeople = people.OrderBy(mySortExpression).ToArray();
于 2009-04-06T19:56:56.460 に答える
8

リフレクションを使用してプロパティにアクセスできます。

public List<Employee> Sort(List<Employee> list, String sortBy, String sortDirection)
{
   PropertyInfo property = list.GetType().GetGenericArguments()[0].
                                GetType().GetProperty(sortBy);

   if (sortDirection == "ASC")
   {
      return list.OrderBy(e => property.GetValue(e, null));
   }
   if (sortDirection == "DESC")
   {
      return list.OrderByDescending(e => property.GetValue(e, null));
   }
   else
   {
      throw new ArgumentOutOfRangeException();
   }
}

ノート

  1. リストを参照渡しするのはなぜですか?
  2. ソート方向には列挙型を使用する必要があります。
  3. プロパティ名を文字列として指定する代わりに、ソートするプロパティを指定するラムダ式を渡すと、よりクリーンなソリューションを得ることができます。
  4. 私の例では、 list == null により NullReferenceException が発生します。このケースをキャッチする必要があります。
于 2009-04-06T19:49:04.747 に答える
6

型が実装している場合、Sort は IComparable インターフェイスを使用します。また、カスタム IComparer を実装することで、ifs を回避できます。

class EmpComp : IComparer<Employee>
{
    string fieldName;
    public EmpComp(string fieldName)
    {
        this.fieldName = fieldName;
    }

    public int Compare(Employee x, Employee y)
    {
        // compare x.fieldName and y.fieldName
    }
}

その後

list.Sort(new EmpComp(sortBy));
于 2009-04-06T19:48:13.750 に答える
5

1.の答え:

名前を文字列として使用して OrderBy に渡すことができる式ツリーを手動で構築できるはずです。または、別の回答で提案されているようにリフレクションを使用することもできますが、これは作業が少ない可能性があります。

編集:これは、式ツリーを手動で構築する実際の例です。(プロパティの名前「値」のみを知っている場合は、X.Value で並べ替えます)。それを行うための一般的な方法を構築できます(すべきです)。

using System;
using System.Linq;
using System.Linq.Expressions;

class Program
{
    private static readonly Random rand = new Random();
    static void Main(string[] args)
    {
        var randX = from n in Enumerable.Range(0, 100)
                    select new X { Value = rand.Next(1000) };

        ParameterExpression pe = Expression.Parameter(typeof(X), "value");
        var expression = Expression.Property(pe, "Value");
        var exp = Expression.Lambda<Func<X, int>>(expression, pe).Compile();

        foreach (var n in randX.OrderBy(exp))
            Console.WriteLine(n.Value);
    }

    public class X
    {
        public int Value { get; set; }
    }
}

ただし、式ツリーを構築するには、関与する型を知る必要があります。これは、使用シナリオで問題になる場合とそうでない場合があります。ソートするタイプがわからない場合は、おそらくリフレクションを使用する方が簡単です。

2.の答え:

はい、Comparer<T>.Default が比較に使用されるため、比較子を明示的に定義しない場合。

于 2009-04-06T19:45:41.900 に答える
4

Rashackが提供するソリューションは、残念ながら値型(int、enumsなど)では機能しません。

あらゆるタイプのプロパティで機能するために、これは私が見つけた解決策です:

public static Expression<Func<T, object>> GetLambdaExpressionFor<T>(this string sortColumn)
    {
        var type = typeof(T);
        var parameterExpression = Expression.Parameter(type, "x");
        var body = Expression.PropertyOrField(parameterExpression, sortColumn);
        var convertedBody = Expression.MakeUnary(ExpressionType.Convert, body, typeof(object));

        var expression = Expression.Lambda<Func<T, object>>(convertedBody, new[] { parameterExpression });

        return expression;
    }
于 2011-03-07T11:52:01.790 に答える
4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

public static class EnumerableHelper
{

    static MethodInfo orderBy = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
    {
        var pi = typeof(TSource).GetProperty(propertyName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        var sourceParam = Expression.Parameter(typeof(IEnumerable<TSource>), "source");
        return 
            Expression.Lambda<Func<IEnumerable<TSource>, IOrderedEnumerable<TSource>>>
            (
                Expression.Call
                (
                    orderBy.MakeGenericMethod(typeof(TSource), pi.PropertyType), 
                    sourceParam, 
                    Expression.Lambda
                    (
                        typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), 
                        Expression.Property(selectorParam, pi), 
                        selectorParam
                    )
                ), 
                sourceParam
            )
            .Compile()(source);
    }

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName, bool ascending)
    {
        return ascending ? source.OrderBy(propertyName) : source.OrderBy(propertyName).Reverse();
    }

}

もう 1 つ、今回は IQueryable の場合:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class IQueryableHelper
{

    static MethodInfo orderBy = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();
    static MethodInfo orderByDescending = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderByDescending" && x.GetParameters().Length == 2).First();

    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, params string[] sortDescriptors)
    {
        return sortDescriptors.Length > 0 ? source.OrderBy(sortDescriptors, 0) : source;
    }

    static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string[] sortDescriptors, int index)
    {
        if (index < sortDescriptors.Length - 1) source = source.OrderBy(sortDescriptors, index + 1);
        string[] splitted = sortDescriptors[index].Split(' ');
        var pi = typeof(TSource).GetProperty(splitted[0], BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.IgnoreCase);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        return source.Provider.CreateQuery<TSource>(Expression.Call((splitted.Length > 1 && string.Compare(splitted[1], "desc", StringComparison.Ordinal) == 0 ? orderByDescending : orderBy).MakeGenericMethod(typeof(TSource), pi.PropertyType), source.Expression, Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), Expression.Property(selectorParam, pi), selectorParam)));
    }

}

次のように、複数の並べ替え基準を渡すことができます。

var q = dc.Felhasznalos.OrderBy(new string[] { "Email", "FelhasznaloID desc" });
于 2010-02-18T12:58:23.980 に答える