C linq查詢之動態OrderBy用法例項

2022-09-26 07:21:13 字數 1823 閱讀 9643

grouplist是原始資料集合,list

sortorder是排序型別,desc 或者asc

sortname是排序屬性名稱

1.使用反射。

private static object getpropertyvalue(object obj, string property)

var resultlist = sortorder == "desc" ? grouplist.orderbyd程式設計客棧escending(p => getpropertyvalue(p, sortname)) : grouplist.orderby(p => getpropertyvalue(p, sortname));

//linq方式:

//var resultlist1 = from p in grouplist orderby getpropertyvalue(p, m.sortname) select p;

if (sortorder == "desc")

resultlist1 = from p in grouplist orderby getpropertyvalue(p, sortname) descending select p;

2.呼叫asqueryable()

將泛型 system.collections.generic.ienumerable 轉換為泛型 system.linq.iqueryable。

var groupquerylist = grouplist.asqueryable();//here

var tmplist = groupquerylist.orderby(sortname, sortorder);

需要如下擴充套件方法:

public static iorderedqueryable orderbydescending(this iqueryable source, string property)

public static iorderedqueryable thenby(this iorderedqueryable source, string property)

public static iordered程式設計客棧queryable thenbydescending(this iorderedqueryable source, string property)

static iorderedqueryable applyorder(iqueryable source, string property, string methodname)

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

rcrlovalyq && method.getgenericarguments().length == 2

&& method.getparameters().length == 2)

.makegenericmethod(typeof(t), type)

.invoke(null, new object );

return (iorderedqueryable)result;

}本文標題: c# linq查詢之動態orderby用法例項

本文位址:

c linq 聯合查詢

linq基本語法及其示例 說明 1 在未作任何說明的情況下,以下用到的db變數都是datacontext的例項物件,宣告語法類似如下 using bp dataclassesdatacontext db new bp dataclassesdatacontext connectionstrings....

C Linq查詢簡介

查詢是一種從資料來源檢索資料的表示式。linq 通過提供一種跨各種資料來源和資料格式使用資料的一致模型。所有 linq 查詢操作都由以下三個不同的操作組成 獲取資料源。建立查詢。執行查詢。2.建立查詢.var numquery from num in numbers where num 2 0 se...

ThinkPHP CURD方法之order方法詳解

thinkphp curd方法的order方法屬於模型的連貫操作方法之一,該www.cppcns.com方法用於對操作的結果排序。具體用i bjsri法如下 model where status 1 order id desc limit 5 select 注意 連貫操作方法i bjsri沒有順序,...