C#对IQueryable<T>、IEnumerable<T>的扩展方法
#region IQueryable<T>的扩展方法 #region 根据第三方条件是否为真是否执行指定条件的查询
/// <summary>
/// 根据第三方条件是否为真是否执行指定条件的查询
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要查询的数据源</param>
/// <param name="where">条件</param>
/// <param name="condition">第三方条件</param>
/// <returns>查询的结果</returns>
public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, Expression<Func<T, bool>> where,
bool condition)
{
if (PublicHelper.CheckArgument(where, "where"))
{
return condition ? source.Where(where) : source;
}
return null;
}
#endregion #region 把IQueryable<T>集合按照指定的属性与排序方式进行排序
/// <summary>
/// 把IQueryable集合按照指定的属性与排序方式进行排序
/// </summary>
/// <typeparam name="T">数据集类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="propName">要排序的属性名称</param>
/// <param name="listSort">排序方式</param>
/// <returns>返回排序后的结果集</returns>
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propName,
ListSortDirection listSort = ListSortDirection.Ascending)
{
if (PublicHelper.CheckArgument(propName, "propName"))
{
return QueryableHelper<T>.OrderBy(source, propName, listSort);
}
return null;
}
#endregion #region 把IQueryable<T>集合按照指定的属性与排序方式进行排序
/// <summary>
/// 把IQueryable集合按照指定的属性与排序方式进行排序
/// </summary>
/// <typeparam name="T">数据集类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="sortCondition">排序条件</param>
/// <returns>返回排序后的结果集</returns>
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, PropertySortCondition sortCondition)
{
if (PublicHelper.CheckArgument(sortCondition, "sortCondition"))
{
return source.OrderBy(sortCondition.PropertyName, sortCondition.ListSortDirection);
}
return null;
}
#endregion #region 把IOrderedQueryable<T>集合按照指定的属性与排序方式进行再排序
/// <summary>
/// 把IOrderedQueryable集合按照指定的属性与排序方式进行排序
/// </summary>
/// <typeparam name="T">数据集类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="propName">要排序的属性名称</param>
/// <param name="listSort">排序方式</param>
/// <returns>返回排序后的结果集</returns>
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propName,
ListSortDirection listSort = ListSortDirection.Ascending)
{
if (PublicHelper.CheckArgument(propName, "propName"))
{
return QueryableHelper<T>.ThenBy(source, propName, listSort);
}
return null;
}
#endregion #region 把IOrderedQueryable<T>集合按照指定的属性与排序方式进行再排序
/// <summary>
/// 把IOrderedQueryable集合按照指定的属性与排序方式进行排序
/// </summary>
/// <typeparam name="T">数据集类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="sortCondition">排序条件</param>
/// <returns>返回排序后的结果集</returns>
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, PropertySortCondition sortCondition)
{
if (PublicHelper.CheckArgument(sortCondition, "sortCondition"))
{
return QueryableHelper<T>.ThenBy(source, sortCondition.PropertyName, sortCondition.ListSortDirection);
}
return null;
}
#endregion #region 多条件排序分页查询
/// <summary>
/// 把IQueryable集合按照指定的属性与排序方式进行排序后,再按照指定的条件提取指定页码指定条目数据
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="where">检索条件</param>
/// <param name="pageIndex">索引</param>
/// <param name="pageSize">页面大小</param>
/// <param name="total">总页数</param>
/// <param name="sortConditions">排序条件</param>
/// <returns>子集</returns>
public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> where, int pageIndex,
int pageSize, out int total, params PropertySortCondition[] sortConditions) where T : class, new()
{
IQueryable<T> temp = null; int i = 0;
if (PublicHelper.CheckArgument(source, "source")
&& PublicHelper.CheckArgument(where, "where")
&& PublicHelper.CheckArgument(pageIndex, "pageIndex")
&& PublicHelper.CheckArgument(pageSize, "pageSize")
&& PublicHelper.CheckArgument(sortConditions, "sortConditions"))
{
//判断是不是首个排序条件
int count = 0;
//得到满足条件的总记录数
i = source.Count(where);
//对数据源进行排序
IOrderedQueryable<T> orderSource = null;
foreach (PropertySortCondition sortCondition in sortConditions)
{
orderSource = count == 0
? source.OrderBy(sortCondition.PropertyName, sortCondition.ListSortDirection)
: orderSource.ThenBy(sortCondition.PropertyName, sortCondition.ListSortDirection);
count++;
}
source = orderSource; temp = source != null
? source.Where(where).Skip((pageIndex - 1) * pageSize).Skip(pageSize)
: Enumerable.Empty<T>().AsQueryable();
} total = i;
return temp; //PublicHelper.CheckArgument(source, "source");
//PublicHelper.CheckArgument(where, "where");
//PublicHelper.CheckArgument(pageIndex, "pageIndex");
//PublicHelper.CheckArgument(pageSize, "pageSize");
//PublicHelper.CheckArgument(sortConditions, "sortConditions"); ////判断是不是首个排序条件
//int count = 0;
////得到满足条件的总记录数
//total = source.Count(where);
////对数据源进行排序
//IOrderedQueryable<T> orderSource = null;
//foreach (PropertySortCondition sortCondition in sortConditions)
//{
// orderSource = count == 0
// ? source.OrderBy(sortCondition.PropertyName, sortCondition.ListSortDirection)
// : orderSource.ThenBy(sortCondition.PropertyName, sortCondition.ListSortDirection);
// count++;
//}
//source = orderSource; //return source != null
// ? source.Where(where).Skip((pageIndex - 1) * pageSize).Skip(pageSize)
// : Enumerable.Empty<T>().AsQueryable();
}
#endregion #region 多条件排序查询
///// <summary>
///// 多条件排序查询
///// </summary>
///// <typeparam name="T">动态类型</typeparam>
///// <param name="source">要排序的数据集</param>
///// <param name="where">检索条件</param>
///// <param name="sortConditions">排序条件</param>
///// <returns>子集</returns>
//public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> where, params PropertySortCondition[] sortConditions) where T : class, new()
//{
// log = LogManager.GetLogger(string.Format("查询表_{0}", typeof(T)));
// IQueryable<T> temp = null;
// Logger("", () =>
// {
// if (PublicHelper.CheckArgument(source, "source")
// && PublicHelper.CheckArgument(where, "where")
// && PublicHelper.CheckArgument(sortConditions, "sortConditions"))
// {
// //判断是不是首个排序条件
// int count = 0;
// //对数据源进行排序
// IOrderedQueryable<T> orderSource = null;
// foreach (PropertySortCondition sortCondition in sortConditions)
// {
// orderSource = count == 0
// ? source.OrderBy(sortCondition.PropertyName, sortCondition.ListSortDirection)
// : orderSource.ThenBy(sortCondition.PropertyName, sortCondition.ListSortDirection);
// count++;
// }
// source = orderSource; // temp = source != null
// ? source.Where(where)
// : Enumerable.Empty<T>().AsQueryable();
// }
// });
// return temp;
//}
#endregion #endregion #region IEnumerable<T>的扩展方法 #region 将集合展开分别转换成字符串,再以指定分隔字符串链接,拼成一个字符串返回
/// <summary>
/// 将集合展开分别转换成字符串,再以指定分隔字符串链接,拼成一个字符串返回
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="collection">要处理的集合</param>
/// <param name="separator">分隔符</param>
/// <returns>拼接后的字符串</returns>
public static string ExpandAndToString<T>(this IEnumerable<T> collection, string separator)
{
List<T> source = collection as List<T> ?? collection.ToList();
if (source.IsEmpty())
{
return "";
} string result = source.Cast<object>()
.Aggregate<object, string>(null, (current, o) => current + String.Format("{0}{1}", o, separator)); return result.Substring(0, result.LastIndexOf(separator, StringComparison.Ordinal));
}
#endregion #region 根据指定条件返回集合中不重复的元素
/// <summary>
/// 根据指定条件返回集合中不重复的元素
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <typeparam name="TKey">动态筛选条件类型</typeparam>
/// <param name="source">要操作的数据源</param>
/// <param name="keySelector">重复数据的筛选条件</param>
/// <returns>不重复元素的集合</returns>
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
{
//取分组集合中每组的第一条数据
return source.GroupBy(keySelector).Select(group => group.First());
}
#endregion #region 根据第三方条件是否为真是否执行指定条件的查询
/// <summary>
/// 根据第三方条件是否为真是否执行指定条件的查询
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要查询的数据源</param>
/// <param name="where">条件</param>
/// <param name="condition">第三方条件</param>
/// <returns>查询的结果</returns>
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, Func<T, bool> where,
bool condition)
{
return condition ? source.Where(where) : source;
}
#endregion #region 判断集合是否为空
/// <summary>
/// 判断集合是否为空
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="collection">要处理的集合</param>
/// <returns>集合为空返回true 不为空返回false</returns>
public static bool IsEmpty<T>(this IEnumerable<T> collection)
{
return !collection.Any();
}
#endregion #endregion #region 其他
/// <summary>
/// 扩展Between 操作符
/// 使用 var query = db.People.Between(person => person.Age, 18, 21);
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="source">当前值</param>
/// <param name="keySelector">拉姆达表达式</param>
/// <param name="low">低</param>
/// <param name="high">高</param>
/// <returns></returns>
public static IQueryable<TSource> Between<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, TKey low, TKey high) where TKey : IComparable<TKey>
{
Expression key = Expression.Invoke(keySelector, keySelector.Parameters.ToArray()); Expression lowerBound = Expression.GreaterThanOrEqual(key, Expression.Constant(low)); Expression upperBound = Expression.LessThanOrEqual(key, Expression.Constant(high)); Expression and = Expression.AndAlso(lowerBound, upperBound); Expression<Func<TSource, bool>> lambda = Expression.Lambda<Func<TSource, bool>>(and, keySelector.Parameters); return source.Where(lambda);
} /// <summary>
/// In
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="values"></param>
/// <returns></returns>
public static bool In<T>(this T value, params T[] values)
{
return values.Contains(value);
} /// <summary>
/// Between
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="i"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static bool Between<T>(this T i, T start, T end) where T : IComparable<T>
{
return i.CompareTo(start) >= 0 && i.CompareTo(end) <= 0;
} /// <summary>
/// And
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool And(this bool left, bool right)
{
return left && right;
} /// <summary>
/// Or
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool Or(this bool left, bool right)
{
return left || right;
} #endregion
C#对IQueryable<T>、IEnumerable<T>的扩展方法的更多相关文章
- IEnumerable接口的扩展方法
/// <summary>/// IEnumerable接口的扩展方法,支持它的实现类是List的情况/// </summary>using System.Collection ...
- IEnumerable<T>与IQueryable<T>以及.net的扩展方法
首先看看继承关系 public abstract class DbSet : DbQuery public abstract class DbQuery : IOrderedQueryable, IQ ...
- 工作总结 for 另类写法 循环加时间 集合合并 也是用的 static class Enumerable (IEnumerable<T>的扩展方法) (IEnumerable<T> 的 工具类) (所有集合 数组都实现IEnumerable<T>)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- 23.C#Queryable的扩展方法(十二章12.1-12.2)
今天要写的知识还真心有点绕呢,对于第一节的内容,其实是把原先在内存中的数据源,换成了从数据库中提取出来的数据.从代码的使用方式上是一样的,直接跳过,来看看IEnumerable和IQueryable的 ...
- 从扩展方法到匿名方法再到LINQ
1.首先我们应该知道什么是扩展方法: 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样 ...
- C#语法糖之第四篇: 扩展方法
今天继续分享C#4.0语法糖的扩展方法,这个方法也是我本人比较喜欢的方法.大家先想想比如我们以前写的原始类型不能满足现在的需求,而需要在该类型中添加新的方法来实现时大家会怎么做.我先说一下我没有学习到 ...
- C#语法糖: 扩展方法(常用)
今天继续分享C#4.0语法糖的扩展方法,这个方法也是我本人比较喜欢的方法.大家先想想比如我们以前写的原始类型不能满足现在的需求,而需要在该类型中添加新的方法来实现时大家会怎么做.我先说一下我没有学习到 ...
- C# LiNq的语法以及常用的扩展方法
首先先来扯一下,这篇博文是我第一次写的,主要是我的一些摘录,希望对大家有所帮助. Linq的基础 •LINQ(读音link):Linq To SQL(过时).Linq To Object.Linq T ...
- 3.4.1 使用过滤式扩展方法(P43-44)
对IEnumerable<T>执行标准并且同样返回IEnumerable<T>的扩展方法,可以使用yield关键字对源数据中的项应用选择标准,已生成精简的结果集. public ...
随机推荐
- Unity 连接WebSocket(ws://)服务器
Unity 连接ws,不用任何插件,忙活了一天终于搞定了,一直连接不上,原来是没有添加header, 代码比较简单,直接贴出来普度众生 using System; using System.Net.W ...
- 06-vue项目02:vuex、Mutation、Action、ElementUI、axios
1.Vuex 1.为什么使用VueX data从最上面的组件,一层层往下传值,一层层的验证 Vue单向数据流 “中央空调“,代理 VueX 解决数据 传值.. 2.Vuex介绍与安装 (1)Vuex官 ...
- Codeforces Round #346 (Div. 2) B题
B. Qualifying Contest Very soon Berland will hold a School Team Programming Olympiad. From each of t ...
- 北京清北 综合强化班 Day5
T1 思路: 输入数据,sort一下, 如果a[i]>sum+1(前缀和) 那么sum+1就一定不会被拼出来, 然后输出即可. 上代码: #include <iostream> #i ...
- 【线性代数】2-3:消元与矩阵的关系(Elimination and Matrix)
title: [线性代数]2-3:消元与矩阵的关系(Elimination and Matrix) toc: true categories: Mathematic Linear Algebra da ...
- Postman请求运行顺序及Workflow
作为一款接口调试利器, Postman的更新迭代速度很快, 不断加入了很多新的功能.使的api设计,测试,监控, Mock,以及团队协作更加方便. 修改执行顺序 在遇到有接口依赖的情况, 我们往往需要 ...
- Docker容器常用命令汇总
Docker常用命令总结如下: # 查看docker详细信息 docker info # 获取当前节点所有容器 docker ps -a # 管理容器生命周期 docker [start|stop|r ...
- conda虚拟环境 相关操作
查询环境 conda env list 或者 conda info --envs 创建环境 conda create -n your_env_name python=3.7 删除环境 conda re ...
- BFS,优先队列优化
题意: 'S' : 起点 'T' : 终点 '#' : 毒气室 'B' :氧气 'P':不消耗步数 每次经过毒气室需要一瓶氧气,氧气可以重复获得,但只能带五瓶氧气,问最少步数 solution: HI ...
- 前端知识点回顾——Javascript篇(三)
数组的冒泡.选择和插入排序法 冒泡排序法(从小到大) function bubble(arr){ for(let i = 0 ;i<arr.length-1;i++){ for(let j = ...