扩展方法名:Filter
支持参数:实体类、JObject
扩展代码:
//白色风车
public static class EntityFrameworkCoreExtensions
{
private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection connection, params object[] parameters)
{
var conn = facade.GetDbConnection();
connection = conn;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd;
}
public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters)
{
var command = CreateCommand(facade, sql, out DbConnection conn, parameters);
var reader = command.ExecuteReader();
var dt = new DataTable();
dt.Load(reader);
reader.Close();
conn.Close();
return dt;
}
public static List<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new()
{
var dt = SqlQuery(facade, sql, parameters);
return dt.ToList<T>();
}
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
var propertyInfos = typeof(T).GetProperties();
var list = new List<T>();
foreach (DataRow row in dt.Rows)
{
var t = new T();
foreach (PropertyInfo p in propertyInfos)
{
if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value)
p.SetValue(t, row[p.Name], null);
}
list.Add(t);
}
return list;
}
//public static List<T> DTToList<T>(this DataTable dt)
//{
// var dataColumn = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList();
// var properties = typeof(T).GetProperties();
// string columnName = string.Empty;
// return dt.AsEnumerable().Select(row =>
// {
// var t = Activator.CreateInstance<T>();
// foreach (var p in properties)
// {
// columnName = p.Name;
// if (dataColumn.Contains(columnName))
// {
// if (!p.CanWrite)
// continue;
// object value = row[columnName];
// Type type = p.PropertyType;
// if (value != DBNull.Value)
// {
// p.SetValue(t, Convert.ChangeType(value, type), null);
// }
// }
// }
// return t;
// }).ToList();
//}
public static DataTable ToDataTable<T>(this List<T> items)
{
DataTable dataTable = new DataTable();
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T obj in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(obj, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// WhereIf扩展
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="condition"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
{
return condition ? query.Where(predicate) : query;
}
/// <summary>
/// WhereIf扩展
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="condition"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, int, bool>> predicate)
{
return condition ? query.Where(predicate) : query;
}
/// <summary>
/// WhereIf扩展
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="condition"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> query, bool condition, Func<T, bool> predicate)
{
return condition ? query.Where(predicate) : query;
}
/// <summary>
/// 条件筛选过滤 (字段的名称、类型一致)
/// </summary>
/// <typeparam name="T">源数据</typeparam>
/// <typeparam name="R">筛选参数实体</typeparam>
/// <param name="query">属性标识[JsonIgnore] 设置该属性不作筛选字段</param>
/// <param name="condition">属性标识[JsonIgnore] 设置该属性不作筛选字段</param>
/// <returns></returns>
public static IQueryable<T> Filter<T, R>(this IQueryable<T> query, R condition) where R : new()
{
//参考 https://www.cnblogs.com/ma-nong01/p/14323430.html https://www.cnblogs.com/doudouzi/p/11897731.html
var dbsel = typeof(T).GetProperties().Where(p => p.CanWrite && !p.CustomAttributes.Any(x => x.AttributeType == typeof(JsonIgnoreAttribute) || x.AttributeType == typeof(NotMappedAttribute))).ToList();
var con = condition.GetType().GetProperties().Where(p => p.CanWrite && !p.CustomAttributes.Any(x => x.AttributeType == typeof(JsonIgnoreAttribute) || x.AttributeType == typeof(NotMappedAttribute))).ToList();
List<MethodCallExpression> mcList = new List<MethodCallExpression>();
List<BinaryExpression> mcList2 = new List<BinaryExpression>();
ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "x");
List<Expression> listexp = new List<Expression>();
foreach (var item in dbsel)
{
foreach (var p in con)
{
var name = p.Name;
if (name.ToLower() == item.Name.ToLower())
{
var type = p.PropertyType;
var val = p.GetValue(condition, null);
if (val != null)
{
//字符串不为空
if (!(type.Name == "String" && string.IsNullOrEmpty(val.ToString())))
{
//传入的是数组
if (type.Name == "List`1")
{
//泛型里的类型与筛选值的类型一致
if (type.GetGenericArguments()?.FirstOrDefault() == item.PropertyType && ((ICollection)val).Count > 0)
{
//参考 https://www.likecs.com/ask-4358604.html#sc=2800
var methodInfo = type.GetMethod("Contains", new Type[] { item.PropertyType });
var list = Expression.Constant(val);
//var param = Expression.Parameter(typeof(T), "j");
var value = Expression.Property(parameterExpression, item);
var body = Expression.Call(list, methodInfo, value);
listexp.Add(body);
}
}
//类型一致
else if (item.PropertyType == type)
{
MemberExpression proerty = Expression.Property(parameterExpression, item);
ConstantExpression constantExpression = Expression.Constant(val, item.PropertyType);
if (item.PropertyType.Name == "String")
{
listexp.Add(Expression.Call(proerty, typeof(string).GetMethod("Contains", new Type[] { item.PropertyType }), new Expression[] { constantExpression }));
}
//else if (item.PropertyType.Name == "Boolean")
//{
// listexp.Add(Expression.Call(proerty, typeof(bool).GetMethod("Equals", new Type[] { typeof(bool) }), new Expression[] { constantExpression }));
//}
//else if (item.PropertyType.Name == "Int32" /*&& !val.ToString().Equals("0")*/)
//{
// listexp.Add(Expression.Call(proerty, typeof(int).GetMethod("Equals", new Type[] { typeof(int) }), new Expression[] { constantExpression }));
//}
else if (item.PropertyType.Name == "DateTime")
{
if (DateTime.TryParse(val?.ToString(), out DateTime parsedDate))
{
var constant = Expression.Constant(parsedDate.Date);
var property = Expression.Property(proerty, "Date");
var exp1 = Expression.Equal(property, constant);
listexp.Add(exp1);
}
}
//else if (item.PropertyType.Name == "Decimal")
//{
// listexp.Add(Expression.Call(proerty, typeof(decimal).GetMethod("Equals", new Type[] { typeof(decimal) }), new Expression[] { constantExpression }));
//}
//else if (item.PropertyType.Name != "Int32" && item.PropertyType.Name != "ICollection`1" && item.PropertyType.Name != "Nullable`1")
//{
// listexp.Add(Expression.Call(proerty, typeof(string).GetMethod("Contains", new Type[] { item.PropertyType }), new Expression[] { constantExpression }));
//}
else if (item.PropertyType.Name == "ICollection`1")
{
}
else if (item.PropertyType.Name == "Nullable`1"/* && !val.ToString().Equals("0")*/)
{
if (type.GetGenericArguments()?.FirstOrDefault() == typeof(DateTime))
{
if (DateTime.TryParse(val?.ToString(), out DateTime parsedDate))
{
var constant = Expression.Constant(parsedDate.Date);
var property = Expression.Property(proerty, "Value");
property = Expression.Property(property, "Date");
var exp1 = Expression.Equal(property, constant);
listexp.Add(exp1);
}
}
else
{
listexp.Add(Expression.Equal(proerty, constantExpression));
}
}
else
{
listexp.Add(Expression.Equal(proerty, constantExpression));
}
}
break;
}
}
}
}
}
Expression<Func<T, bool>> exp = Expression.Lambda<Func<T, bool>>(MethodCall(listexp), new ParameterExpression[] { parameterExpression });
return exp != null ? query.Where(exp) : query;
}
/// <summary>
/// 条件筛选过滤
/// </summary>
/// <typeparam name="T">源数据</typeparam>
/// <param name="query">属性标识[JsonIgnore] 设置该属性不作筛选字段</param>
/// <param name="Jobj">JObject 筛选参数</param>
/// <returns></returns>
public static IQueryable<T> Filter<T>(this IQueryable<T> query, JObject Jobj) where T : new()
{
var condition = Jobj.ToObject<T>();
return query.Filter(condition);
}
/// <summary>
/// 递归拼接 条件
/// </summary>
/// <param name="conditions"></param>
/// <returns></returns>
private static Expression MethodCall(IEnumerable<Expression> conditions)
{
if (conditions == null || conditions.Count() == 0)
{
return Expression.Constant(true, typeof(bool));
}
else if (conditions.Count() == 1)
{
return conditions.First();
}
else
{
Expression left = MethodCall(conditions.Take(1).ToList());
Expression right = MethodCall(conditions.Skip(1).ToList());
return Expression.AndAlso(left, right);
}
}
}
View Code用法:
var list=db.tableA.Filter(obj).ToList();
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano
question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt