IEnumerable<T> / IQueryable<T> の動的 LINQ OrderBy
-
09-06-2019 - |
質問
で例を見つけました VS2008 の例 SQL のような文字列を使用できるようにする動的 LINQ の場合 (例: OrderBy("Name, Age DESC"))
注文用に。残念ながら、含まれているメソッドは次の場合にのみ機能します。 IQueryable<T>
;。この機能を有効にする方法はありますか IEnumerable<T>
?
解決
たまたまこのオールディーズに遭遇しました...
ダイナミック LINQ ライブラリを使用せずにこれを行うには、次のコードだけが必要です。これは、ネストされたプロパティを含む最も一般的なシナリオをカバーします。
動作させるには IEnumerable<T>
を経由するいくつかのラッパーメソッドを追加できます AsQueryable
- ただし、以下のコードがコアです Expression
ロジックが必要です。
public static IOrderedQueryable<T> OrderBy<T>(
this IQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(
this IQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(
this IOrderedQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(
this IOrderedQueryable<T> source,
string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(
IQueryable<T> source,
string property,
string methodName)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach(string prop in props) {
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] {source, lambda});
return (IOrderedQueryable<T>)result;
}
編集:それを混ぜるともっと楽しくなります dynamic
- ただし、注意してください dynamic
LINQ-to-Objects にのみ適用されます (ORM などの式ツリーでは実際には表現できません) dynamic
クエリ - MemberExpression
サポートしていません)。ただし、LINQ-to-Objects を使用してそれを行う方法があります。の選択に注意してください Hashtable
これは、有利なロック セマンティクスによるものです。
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;
static class Program
{
private static class AccessorCache
{
private static readonly Hashtable accessors = new Hashtable();
private static readonly Hashtable callSites = new Hashtable();
private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(
string name)
{
var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
if(callSite == null)
{
callSites[name] = callSite = CallSite<Func<CallSite, object, object>>
.Create(Binder.GetMember(
CSharpBinderFlags.None,
name,
typeof(AccessorCache),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(
CSharpArgumentInfoFlags.None,
null)
}));
}
return callSite;
}
internal static Func<dynamic,object> GetAccessor(string name)
{
Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
lock (accessors )
{
accessor = (Func<dynamic, object>)accessors[name];
if (accessor == null)
{
if(name.IndexOf('.') >= 0) {
string[] props = name.Split('.');
CallSite<Func<CallSite, object, object>>[] arr
= Array.ConvertAll(props, GetCallSiteLocked);
accessor = target =>
{
object val = (object)target;
for (int i = 0; i < arr.Length; i++)
{
var cs = arr[i];
val = cs.Target(cs, val);
}
return val;
};
} else {
var callSite = GetCallSiteLocked(name);
accessor = target =>
{
return callSite.Target(callSite, (object)target);
};
}
accessors[name] = accessor;
}
}
}
return accessor;
}
}
public static IOrderedEnumerable<dynamic> OrderBy(
this IEnumerable<dynamic> source,
string property)
{
return Enumerable.OrderBy<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(
this IEnumerable<dynamic> source,
string property)
{
return Enumerable.OrderByDescending<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(
this IOrderedEnumerable<dynamic> source,
string property)
{
return Enumerable.ThenBy<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(
this IOrderedEnumerable<dynamic> source,
string property)
{
return Enumerable.ThenByDescending<dynamic, object>(
source,
AccessorCache.GetAccessor(property),
Comparer<object>.Default);
}
static void Main()
{
dynamic a = new ExpandoObject(),
b = new ExpandoObject(),
c = new ExpandoObject();
a.X = "abc";
b.X = "ghi";
c.X = "def";
dynamic[] data = new[] {
new { Y = a },
new { Y = b },
new { Y = c }
};
var ordered = data.OrderByDescending("Y.X").ToArray();
foreach (var obj in ordered)
{
Console.WriteLine(obj.Y.X);
}
}
}
他のヒント
複雑さもなく簡単すぎる:
- 追加
using System.Linq.Dynamic;
頂点で。 - 使用
vehicles = vehicles.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();
答えが見つかりました。使用できます .AsQueryable<>()
拡張メソッドを使用してリストを IQueryable に変換し、それに対して動的順序を実行します。
ちょうどこの質問に遭遇しました。
上記の Marc の applyOrder 実装を使用して、次のような SQL のような文字列を処理する Extension メソッドをまとめました。
list.OrderBy("MyProperty DESC, MyOtherProperty ASC");
詳細はこちらでご覧いただけます: http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html
リフレクションを使用して並べ替えたいプロパティを取得するとうまくいくと思います。
IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
where some criteria
orderby GetPropertyValue(enumerable,"SomeProperty")
select enumerable
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
リフレクションを使用すると、プロパティに直接アクセスするよりも大幅に時間がかかるため、パフォーマンスを調査する必要があることに注意してください。
他の人が言ったことに基づいて構築しているだけです。以下は非常にうまく機能することがわかりました。
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> input, string queryString)
{
if (string.IsNullOrEmpty(queryString))
return input;
int i = 0;
foreach (string propname in queryString.Split(','))
{
var subContent = propname.Split('|');
if (Convert.ToInt32(subContent[1].Trim()) == 0)
{
if (i == 0)
input = input.OrderBy(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenBy(x => GetPropertyValue(x, subContent[0].Trim()));
}
else
{
if (i == 0)
input = input.OrderByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
}
i++;
}
return input;
}
私はこの質問をつまずき、linq複数のオーダー担当条項を探していますが、これが著者が探していたものだったのかもしれません
その方法は次のとおりです。
var query = pets.OrderBy(pet => pet.Name).ThenByDescending(pet => pet.Age);
これをやろうとしていましたが、問題がありました ケティル・ワトネダルの解決策 私はインライン linq 構文を使用しないため、メソッド形式の構文を好みます。私の具体的な問題は、カスタムメソッドを使用して動的並べ替えを実行しようとしたことでした IComparer
.
私の解決策は次のようになりました。
次のような IQueryable クエリがあるとします。
List<DATA__Security__Team> teams = TeamManager.GetTeams();
var query = teams.Where(team => team.ID < 10).AsQueryable();
実行時の並べ替えフィールド引数を指定すると、次のようになります。
string SortField; // Set at run-time to "Name"
動的な OrderBy は次のようになります。
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));
そして、これは GetReflectedPropertyValue() という小さなヘルパー メソッドを使用しています。
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
最後にもう 1 つ - 欲しいと言いましたが、 OrderBy
カスタムを使用するには IComparer
- やりたかったから 自然な選別.
そのためには、 OrderBy
に:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());
見る この郵便受け コードの場合 NaturalSortComparer()
.
それを追加することもできます:
public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
//parse the string into property names
//Use reflection to get and sort by properties
//something like
foreach( string propname in queryString.Split(','))
input.OrderBy( x => GetPropertyValue( x, propname ) );
// I used Kjetil Watnedal's reflection example
}
の GetPropertyValue
関数はからです ケティル・ワトネダルの答え
問題はその理由だろう。そのような並べ替えは、コンパイル時ではなく実行時に例外をスローします (D2VIANT の回答のように)。
Linq to Sql を扱っており、orderby が式ツリーである場合は、とにかく実行のために SQL に変換されます。
他に面白いと思ったものがあります。ソースが DataTable の場合、Dynamic Linq を使用せずに動的並べ替えを使用できます。
DataTable orders = dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
orderby order.Field<DateTime>("OrderDate")
select order;
DataView view = query.AsDataView();
bindingSource1.DataSource = view;
参照: http://msdn.microsoft.com/en-us/library/bb669083.aspx (DataSetExtensions の使用)
これを DataView に変換するもう 1 つの方法を次に示します。
DataTable contacts = dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
view.Sort = "LastName desc, FirstName asc";
bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();
マールテンさんのおかげです(LINQ で PropertyInfo オブジェクトを使用してコレクションをクエリする)私はこの解決策を手に入れました:
myList.OrderByDescending(x => myPropertyInfo.GetValue(x, null)).ToList();
私の場合、「ColumnHeaderMouseClick」(WindowsForm) で作業していたので、押された特定の列とそれに対応する PropertyInfo を見つけました。
foreach (PropertyInfo column in (new Process()).GetType().GetProperties())
{
if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)
{}
}
または
PropertyInfo column = (new Process()).GetType().GetProperties().Where(x => x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();
(列名がオブジェクトのプロパティと一致していることを確認してください)
乾杯
たくさん検索した結果、これが私にとってはうまくいきました:
public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source,
string orderByProperty, bool desc)
{
string command = desc ? "OrderByDescending" : "OrderBy";
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command,
new[] { type, property.PropertyType },
source.AsQueryable().Expression,
Expression.Quote(orderByExpression));
return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression);
}
IEnumerable を IQueryable に変換できます。
items = items.AsQueryable().OrderBy("Name ASC");
代替ソリューションでは、次のクラス/インターフェイスを使用します。これは実際には動的ではありませんが、機能します。
public interface IID
{
int ID
{
get; set;
}
}
public static class Utils
{
public static int GetID<T>(ObjectQuery<T> items) where T:EntityObject, IID
{
if (items.Count() == 0) return 1;
return items.OrderByDescending(u => u.ID).FirstOrDefault().ID + 1;
}
}
この回答は、提供されたソリューションの例を必要とするコメントへの回答です。 @ジョン・シーハン - ランスコープ
他の人のために例を教えてください。
DAL (データアクセス層)、
IEnumerable バージョン:
public IEnumerable<Order> GetOrders()
{
// i use Dapper to return IEnumerable<T> using Query<T>
//.. do stuff
return orders // IEnumerable<Order>
}
IQueryable バージョン
public IQueryable<Order> GetOrdersAsQuerable()
{
IEnumerable<Order> qry= GetOrders();
//use the built-in extension method AsQueryable in System.Linq namespace
return qry.AsQueryable();
}
Asp.net の GridView などのバインドに IQueryable バージョンを使用できるようになり、並べ替えのメリットが得られます (IEnumerable バージョンを使用して並べ替えることはできません)。
Dapper を ORM として使用し、IQueryable バージョンを構築し、asp.net の GridView での並べ替えを非常に簡単に利用しました。
最初の動的インストールツール --> NuGet パッケージ マネージャー --> パッケージ マネージャー コンソール
install-package System.Linq.Dynamic
追加 名前空間 using System.Linq.Dynamic;
今すぐ使用できます OrderBy("Name, Age DESC")
List を IEnumerable または Iquerable に変換し、System.LINQ.Dynamic 名前空間を使用して追加すると、System.LINQ.Dynamic からデフォルトで提供される OrderBy メソッドにプロパティ名をカンマ区切りの文字列で指定できます。
動的を使用する linq
追加するだけです using System.Linq.Dynamic;
そして、これを次のように使用して、すべての列を並べ替えます。
string sortTypeStr = "ASC"; // or DESC
string SortColumnName = "Age"; // Your column name
query = query.OrderBy($"{SortColumnName} {sortTypeStr}");
var result1 = lst.OrderBy(a=>a.Name);// for ascending order.
var result1 = lst.OrderByDescending(a=>a.Name);// for desc order.