之前网上搜索的相关方法都是使用了反射的方法来动态获取字段,以实现动态linq排序,但是因为项目组觉得此方法效率低下,所以不予采纳。

所以有了以下代码

 public interface IBase{
dynamic GetField(string field);
} public class Employee : IBase
{
public int ID { get; set; }
public string FName { get; set; }
public int Age { get; set; }
public char Sex { get; set; } public dynamic GetField(string field)
{
switch (field.ToUpper()) {
case "ID":
return ID;
case "FNAME":
return FName;
case "AGE":
return Age;
case "SEX":
return Sex;
default:
return ID;
}
}
}

  这是实体类,缺点是必须实现接口方法GetField,但这也是重点。

以下是对应的排序方法

/// <summary>
/// 对结果集进行排序
/// </summary>
/// <param name="source">结果集</param>
/// <param name="dict">参数列表KEY:OrderBy Ascending VALUE:以,分隔</param>
/// <returns></returns>
protected List<IBase> OrderBy(List<IBase> source, Dictionary<string, string> dict)
{
if (dict.ContainsKey("OrderBy"))
{
try
{
string[] Order = dict["OrderBy"].Split(',');
string[] ascend = dict.ContainsKey("Ascending") ? dict["Ascending"].Split(',') : new string[] { "1" };
IOrderedEnumerable<IBase> current = null;
if (ascend[0] == "1")
current = source.OrderBy(p => p.GetField(Order[0]));
else
current = source.OrderByDescending(p => p.GetField(Order[0])); int index = 0;
for (int i = 1; i < Order.Length; i++)
{
index = ascend.Length > i ? i : ascend.Length - 1;
if (ascend[index] == "1")
current = current.ThenBy(p => p.GetField(Order[i]));
else
current = current.ThenByDescending(p => p.GetField(Order[i]));
} return current.ToList();
}
catch { }
}
return source;
}

  以下是测试方法

public void LinqOrder()
{
var empList = new List<Employee>();
Random r = new Random();
int length = 10000000; Console.WriteLine(string.Format("开始装载数据({0})...", length));
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < length; i++)
{
empList.Add(new Employee()
{
ID = i,
FName = "A" + i,
Age = r.Next(0, 100),
Sex = r.Next(0, 1) == 1 ? 'F' : 'M'
});
}
sw.Stop();
Console.WriteLine(string.Format("{0}条数据装载完成,时间为:{1}", length, sw.ElapsedMilliseconds)); Console.WriteLine("开始转换数据,Employee to IBase");
sw = new Stopwatch();
sw.Start();
var list = empList.ToList<IBase>();
sw.Stop();
Console.WriteLine(string.Format("{0}条数据转换,Employee to IBase,时间为:{1}", length, sw.ElapsedMilliseconds)); Dictionary<string, string> dict = new Dictionary<string, string>();
dict["OrderBy"] = "Age,Sex";
dict["Ascending"] = "1,1";
Console.WriteLine("开始排序");
sw = new Stopwatch();
sw.Start();
OrderBy(list, dict);
sw.Stop();
Console.WriteLine(string.Format("{0}条数据使用dynamic排序时间为:{1}", length, sw.ElapsedMilliseconds)); Console.WriteLine("开始普通排序");
sw = new Stopwatch();
sw.Start();
empList.OrderBy(p => p.Age).ThenBy(p => p.Sex).ToList();
sw.Stop();
Console.WriteLine(string.Format("{0}条数据使用字段排序时间为:{1}", length, sw.ElapsedMilliseconds));
}

  以下是测试结果

linq 动态排序,不使用反射的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为s ...

  2. LinQ动态排序

    LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使2 ...

  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(17)-LinQ动态排序

    系列目录 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使20行的代 ...

  4. 使用Linq动态排序

    Linq排序很方便,如果能动态创建Expression再排序就更方便了. 正序还是倒序排列 var order = typeof(Enumerable).GetMember(direction == ...

  5. MVC Linq动态排序

    在nuget 中searh System.Linq.Dynamic 安装对应的版本, 这样都可以使用了 var orderExpression = string.Format("{0} {1 ...

  6. linq 动态排序 order by

    项目查询数据库使用的是linq 语法,可是后期需要用到不同字段的排序.各种纠结! 在网上找了各种资料 后面才找到两种方法 using System; using System.Collections. ...

  7. linq 动态排序

    /// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typepar ...

  8. Linq 动态查询排序

    Linq的排序一般是这样写的: query.OrderBy(x => x.Tel).Skip().Take(); 实际使用中排序字段可能是通过字符类型的参数来设置的,于是想这样实现: query ...

  9. linq扩展之动态排序

    前两天看QQ群里面,一位朋友问的问题,说在linq中怎么实现动态排序呢,自己想了半天,没有头绪,网上找了下相关的资料,看了下,收益挺多,记录下来. 之前我们没有如果不知道动态排序的方法的话,我们可能会 ...

随机推荐

  1. StringUtils判断字符串是否为空的方法

    public static boolean isEmpty(String str)   判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0   下面是 Stri ...

  2. Android RecyclerView使用详解(二)

    在上一篇(RecyclerView使用详解(一))文章中简单的介绍了RecyclerView的基本用法,接下来要来讲讲RecyclerView的更多用法,要实现不同的功能效果,大部分都还是在于Recy ...

  3. mysql的password()函数和md5函数

    password用于修改mysql的用户密码,如果是应用与web程序建议使用md5()函数, password函数旧版16位,新版41位,可用select length(password('12345 ...

  4. 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:4.安装Oracle RAC FAQ-4.4.无法图形化安装Grid Infrastructure

    无法图形化安装: [grid@linuxrac1 grid]$ ./runInstaller Starting Oracle Universal Installer... Checking Temp ...

  5. linux 开机自动启动脚本方法

    通过现场对这次天津iptv demo项目的调测.对iptv这套系统有了更好的认识和理解.由于iptv本身需要安装许多服务.而现场实施中有没有把这些需要启动服务的脚本加入到开 机自动运行中.如果服务器重 ...

  6. Ajax实现搜索栏中输入时的自动提示功能

    使用 jQuery(Ajax)/PHP/MySQL实现自动完成功能 JavaScript代码: <script src="jquery-1.2.1.pack.js" type ...

  7. IGF职业组比赛

    IGF职业组比赛 参赛资格: 面向亚太区所有独立游戏开发者(参见详细规则) 截止日期: 2015年7月20日 2015年IGF职业组七大奖项设置如下: * 最佳游戏(RMB20, 000) * 最佳移 ...

  8. Leetcode 225 Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  9. WebService调用一对多关联关系时出现 死循环:A cycle is detected in...

    通过WebService调用一对多关联关系时引起的问题:A cycle is detected in the object graph 具体异常信息: org.apache.cxf.intercept ...

  10. Spark on Yarn遇到的几个问题

    1 概述 Spark的on Yarn模式,其资源分配是交给Yarn的ResourceManager来进行管理的,但是目前的Spark版本,Application日志的查看,只能通过Yarn的yarn ...