linq 动态排序,不使用反射
之前网上搜索的相关方法都是使用了反射的方法来动态获取字段,以实现动态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 动态排序,不使用反射的更多相关文章
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为s ...
- LinQ动态排序
LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使2 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(17)-LinQ动态排序
系列目录 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使20行的代 ...
- 使用Linq动态排序
Linq排序很方便,如果能动态创建Expression再排序就更方便了. 正序还是倒序排列 var order = typeof(Enumerable).GetMember(direction == ...
- MVC Linq动态排序
在nuget 中searh System.Linq.Dynamic 安装对应的版本, 这样都可以使用了 var orderExpression = string.Format("{0} {1 ...
- linq 动态排序 order by
项目查询数据库使用的是linq 语法,可是后期需要用到不同字段的排序.各种纠结! 在网上找了各种资料 后面才找到两种方法 using System; using System.Collections. ...
- linq 动态排序
/// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typepar ...
- Linq 动态查询排序
Linq的排序一般是这样写的: query.OrderBy(x => x.Tel).Skip().Take(); 实际使用中排序字段可能是通过字符类型的参数来设置的,于是想这样实现: query ...
- linq扩展之动态排序
前两天看QQ群里面,一位朋友问的问题,说在linq中怎么实现动态排序呢,自己想了半天,没有头绪,网上找了下相关的资料,看了下,收益挺多,记录下来. 之前我们没有如果不知道动态排序的方法的话,我们可能会 ...
随机推荐
- 【转】NSArray排序方法
原文网址:http://www.cnblogs.com/xiaobaizhu/archive/2013/06/05/3119983.html 从网上查的,非常方便的排序api,功能也很强大 1.sor ...
- table 锁定表头,出滚动对齐
前一段时间来了一个汇总的需求,想锁定表头,这个问题在网上找了老半天,实现起来都比较麻烦,经过这几天的摸索终于找到一个简洁的处理方法 下面介绍一下如何处理的: 1.thead 和tbody 放两个tab ...
- IE6对CSS支持Bug收集
1.IE6双外边距 在IE6下,如果对元素设置了浮动,同时又设置了margin-left或者margin-right,margin值会加倍. 例如,设置margin-left:10px在IE6下会显示 ...
- Asp.net 身份验证方式?
[Forms 身份验证] 通过其可将没有通过身份验证的请求重定向到使用 HTTP 客户端重定向的 HTML 窗体的系统.用户提供凭据并提交该窗体.如果应用程序验证该请求,系统就会发出包含凭据或密钥的 ...
- Linux 通过YUM安装rzsz
yum自动安装: yum install lrzsz
- python 抽象类、抽象方法的实现
由于python 没有抽象类.接口的概念,所以要实现这种功能得abc.py 这个类库,具体方式如下 from abc import ABCMeta, abstractmethod #抽象类 class ...
- CentOS 5.5 快速安装MariaDB-5.5.35
被网上各种教程坑的不轻T,T,5.5下不升级yum的情况下想快速安装还真有点费劲 至于源码编译安装坑貌似更多 而且在小内存的VPS上编译实在费力 下载地址 http://yum.mariadb.org ...
- (转)PHP开发框架浅析
开发框架的定义我没有找到很准确的描述,下面几句话基本概括了开发框架的的功能和用途 框架是一种应用程序的半成品: 框架就像是人的骨骼一样: 框架是一组可复用的组件: 框架是一个可复用的设计构件…… 简而 ...
- always NetWork Performance measure Tools
1,iperf key feature:Measuring TCP and UDP BandWidth Performance Iperf features; *TCP .Measure bandwi ...
- shell脚本操作mysql库
shell脚本操作mysql数据库-e参数执行各种sql(指定到处编码--default-character-set=utf8 -s,去掉第一行的字段名称信息-N) 2011-05-11 18:18: ...