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中怎么实现动态排序呢,自己想了半天,没有头绪,网上找了下相关的资料,看了下,收益挺多,记录下来. 之前我们没有如果不知道动态排序的方法的话,我们可能会 ...
随机推荐
- org.hibernate.MappingException: duplicate import异常
在开发hibernate时,一起多谢ORM类和映射文件时,报出:org.hibernate.MappingException: duplicate import com.XXX异常 解决方案: 检查你 ...
- tilecache2.11在windows apache2.22安装部署
tilecache2.11在windows apache2.22安装部署 蔡建良 2013-09-03 一.安装环境 操作系统: Windows7 32位 Apache2.22 Python2.5 m ...
- Codeforces Round #215 (Div. 2) D题(离散化+hash)
D. Sereja ans Anagrams time limit per test 1 second memory limit per test 256 megabytes input standa ...
- Excel的最大行数
使用Excel2007或Excel2010,在“另存为” 菜单中可以选择为“Excel 07-2003 工作薄”,从中我们可以看出,到了2007版以后,存储格式变了,简单一点从扩展名便可以看出,一个是 ...
- 使用SchemaSpy逆向工程生成数据库依赖关系使用SchemaSpy工具可以快速的从数据库中得到
使用SchemaSpy逆向工程生成数据库依赖关系 使用SchemaSpy工具可以快速的从数据库中得到表的依赖关系,同时生成一个生动的“表图”结合的报告.方便快速了解数据库中的数据库对象间关系,类 ...
- WCF服务通过防火墙怎么设置
设置防火墙 1.首先点击控制面板->系统与安全->Window防火墙->点击允许程序通过Windows防火墙 2.查找Windows Communication Foundation ...
- 设置UIImage 圆角
//设置UIImage圆角 @interface UIImage(UIRoundedRectImage) + (id) createRoundedRectImage:(UIImage*)image s ...
- 性能测试指标&说明 [解释的灰常清楚哦!!]
详见: 浅谈软件性能测试中关键指标的监控与分析 http://www.51testing.com/html/18/n-3549018.html
- while (cin>>str)退出死循环
今天在练习的时候突然发现了这个问题,百度之感觉还挺常见的,故记之! //题目描述 // //写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串. // //输入描述 : //输入一个 ...
- 转-问自己:UI设计注意的十个问题
UI 设计需要自问的 10个问题 UI 设计的魅力在于,你不仅需要适当的技巧,更要理解用户与程序的关系.一个有效的用户界面关注的是用户目标的实现,包括视觉元素与功能操作在内的所有东西都需要完整一致 ...