/// <summary> /// The FilterHackerNews. /// </summary> /// <param name="hackerNewsItemList">The hackerNewsItemList<see cref="IList{HackerNewsItem}"/>.</param> /// <param name="filterField">The filterField<see cref="HackerNewsFieldEnum"/>.</param> /// <param name="filterOperation">The filterOperation<see cref="HackerNewsFilterOperationEnum"/>.</param> /// <param name="orderByField">The orderByField<see cref="HackerNewsFieldEnum"/>.</param> /// <param name="orderByFieldDesc">The orderByFieldDesc<see cref="bool"/>.</param> /// <returns>The <see cref="IList{HackerNewsItem}"/>.</returns> private IList <HackerNewsItem> FilterHackerNews(IList <HackerNewsItem> hackerNewsItemList, HackerNewsFieldEnum filterField, HackerNewsFilterOperationEnum filterOperation, HackerNewsFieldEnum orderByField, bool orderByFieldDesc) { LambdaExpressionBuilder <HackerNewsItem> expressionBuilder = new LambdaExpressionBuilder <HackerNewsItem>(); Expression <Func <HackerNewsItem, bool> > filteringQuery = GetHackerNewsItemExpressionFilter(expressionBuilder, filterField, filterOperation); Expression <Func <HackerNewsItem, object> > sortingQuery = GetHackerNewsItemExpressionSort(expressionBuilder, orderByField, orderByFieldDesc); // DEBUG: To check the final value if (filteringQuery != null) { hackerNewsItemList = hackerNewsItemList.Where(filteringQuery.Compile()).ToList(); } if (sortingQuery != null) { if (orderByFieldDesc) { hackerNewsItemList = hackerNewsItemList.OrderByDescending(sortingQuery.Compile()).ToList(); } else { hackerNewsItemList = hackerNewsItemList.OrderBy(sortingQuery.Compile()).ToList(); } } return(hackerNewsItemList); }
public string ShowFinished() { int intPageIndex = Request["PageIndex"].ToInt32(); int intPageSize = Request["PageSize"].ToInt32(); int intState = Request["State"].ToInt(); var listFilter = new List <Utility.Filter>(); //动态查询表达式 if (intState <= 10 && intState >= 0) { listFilter.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Enable), true)); } else { listFilter.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Disable), true)); } //动态查询表达式 listFilter.Add(Utility.Filter.Add(string.Empty, Op.Contains, string.Empty, true)); var expTask = LambdaExpressionBuilder.GetExpressionByAndAlso <Task>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add("UID", "desc"); //分页获取数据 Page <Temp> listTaskTemp = AllServices.TaskService.GetFinishedByPage(intPageIndex, intPageSize); return(CommonResult.Instance(1, null, listTaskTemp).ToJson()); }
public string UnfinishedTaskList() { int intPageIndex = Request["PageIndex"].ToInt32(); int intPageSize = Request["PageSize"].ToInt32(); string strField = Request["Field"].ToStr(); string strFieldValue = Request["FieldValue"].ToStr(); int intState = Request["State"].ToInt32(); var listFilter = new List <Utility.Filter>(); //动态查询表达式 listFilter.Add(Utility.Filter.Add(strField, Op.Equals, strFieldValue, true)); listFilter.Add(Utility.Filter.Add("DocumentUID", Op.Equals, "0", true)); if (intState <= 10) { listFilter.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Enable), true)); } else { listFilter.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Disable), true)); } var expTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <TaskList>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add("UID", "desc"); //分页全部获取数据 Page <TaskList> listTaskList = AllServices.TaskListService.GetByPage(intPageIndex, intPageSize, expTaskList, dicOrderBy); //AllServices.TaskService.GetByPage(1,500,null,null) return(listTaskList.ToJson()); }
public Task <List <M> > FindAllByEntity(Dictionary <string, string> request, ServerCallContext context) { return(Task.Run(() => { FilterCollection _filterCollection = new FilterCollection(); Type tType = typeof(M); PropertyInfo propertyInfo; foreach (var key in request.Keys) { propertyInfo = tType.GetProperty(key); List <Filter> filter = new List <Filter> { new Filter { PropertyName = key, Value = request[key].ChangeTypeExtend(propertyInfo), Operation = AttributeModel.ExpressionOptions.Equals } }; _filterCollection.Add(filter); } List <M> mList = baseService().FindAll(LambdaExpressionBuilder.GetExpression <M>(_filterCollection)).Result; return mList; })); }
private static IQueryable <T> Where <T>(this IQueryable <T> source, QueryModel queryModel) { var lambdaExp = LambdaExpressionBuilder.BuildLambda <T>(queryModel); var lambda = lambdaExp.Compile(); return(source.Where(lambda).AsQueryable()); }
public void Null_Or_Empty_Conditions_Should_Return_Ture() { var searchParameters = new SearchParameters(); searchParameters.Query = new QueryModel(); var lambda = LambdaExpressionBuilder.BuildLambda <Foo>(searchParameters.Query); var where = lambda.Compile(); var result = _fooList.Where(where); Assert.IsTrue(result.Count() == 4); }
/// <summary> /// 根据多个FolderNo获取文件夹信息 /// </summary> /// <param name="intFolderID"></param> /// <returns></returns> public List <Folder> GetByIDs(int[] intFolderUIDs) { var listFilter = new List <Utility.Filter>(); foreach (int i in intFolderUIDs) { //动态查询表达式 listFilter.Add(Utility.Filter.Add("UID", Op.Equals, i, true)); } var expTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <Document>(listFilter); Expression <Func <Folder, bool> > whereLambda = null; List <Folder> list = db.Folder.Where(whereLambda).ToList(); return(list); }
public void Contains_Test() { var searchParameters = new SearchParameters(); searchParameters.Query = new QueryModel(); searchParameters.Query.Add(new Condition() { Field = "StringValue", Op = Operation.Contains, Value = "有朋" }); var lambda = LambdaExpressionBuilder.BuildLambda <Foo>(searchParameters.Query); var where = lambda.Compile(); var result = _fooList.Where(where); Assert.IsTrue(result.Count() == 1); }
public string GetTask() { int intUID = Request["UID"].ToInt32(); var listFilter = new List <Utility.Filter>(); //动态查询表达式 listFilter.Add(Utility.Filter.Add(string.Empty, Op.Contains, string.Empty, true)); var expTask = LambdaExpressionBuilder.GetExpressionByAndAlso <Task>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add("UID", "desc"); //分页获取数据 Task task = AllServices.TaskService.GetByID(intUID); return(CommonResult.Instance(1, null, task).ToJson()); }
public void StdIn_Test() { var searchParameters = new SearchParameters(); searchParameters.Query = new QueryModel(); searchParameters.Query.Add(new Condition() { Field = "IntValue", Op = Operation.StdIn, Value = new List <int> { 10, 12 } }); var lambda = LambdaExpressionBuilder.BuildLambda <Foo>(searchParameters.Query); var where = lambda.Compile(); var result = _fooList.Where(where); Assert.IsTrue(result.Count() == 2); }
// 使用表达式树获得动态拼接where条件 private Expression <Func <SMT_PTContextView, bool> > GetWhereExpression(string filterItems, string field) { var items = filterItems.Replace("空白", string.Empty).Split(','); var filter = new List <Filter>(); foreach (var item in items) { filter.Add(new Filter() { Operation = Op.Equals, PropertyName = field, Value = item }); } var filters = new FilterCollection { filter }; return(LambdaExpressionBuilder.GetExpression <SMT_PTContextView>(filters)); }
public string Show() { int intPageIndex = Request["PageIndex"].ToInt32(); int intPageSize = Request["PageSize"].ToInt32(); var listFilter = new List <Utility.Filter>(); //动态查询表达式 listFilter.Add(Utility.Filter.Add(string.Empty, Op.Contains, string.Empty, true)); var expTask = LambdaExpressionBuilder.GetExpressionByAndAlso <Task>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add("UID", "desc"); //分页获取数据 Page <Task> listTask = AllServices.TaskService.GetByPage(intPageIndex, intPageSize, expTask, dicOrderBy); return(CommonResult.Instance(1, null, listTask).ToJson()); }
public IEnumerable <CompanyDTO> GetCompanies(int?Id, string companyName, string countryCode, int?companyType) { try { LambdaExpressionBuilder expressionBuilder = new LambdaExpressionBuilder(); List <CompanyDTO> companies = new List <CompanyDTO>(); using (ISession session = DatabaseHelper.OpenSession()) { if (Id != null) { expressionBuilder = expressionBuilder.WithId(Id); companies = session.Query <CompanyEntity>() .Where(expressionBuilder.Build()).Select(x => new CompanyDTO(x)) .ToList(); } else { if (companyType != null) { expressionBuilder = expressionBuilder.WithCompanyType(companyType); } if (companyName != null) { expressionBuilder = expressionBuilder.WithCompanyName(companyName); } if (countryCode != null) { expressionBuilder = expressionBuilder.WithCountryCode(countryCode); } companies = session.Query <CompanyEntity>() .Where(expressionBuilder.Build()).Select(x => new CompanyDTO(x)) .ToList(); } } return(companies); } catch (Exception ex) { return(null); } }
public void Test_SpecialCase() { var list = new List <Foo>(); var query = new QueryModel(); query.Add(new Condition() { Field = "p2", Op = Operation.Equals, Value = 1 }); query.Add(new Condition() { Field = "p2", Op = Operation.StdIn, Value = new List <int> { 1, 2, 3 } }); var lambdaExp = LambdaExpressionBuilder.BuildLambda <Foo>(query); var lambda = lambdaExp.Compile(); list = list.Where(lambda).ToList(); }
public LambdaExpression CreateExpression(Type elementType, string propertyName) { var names = propertyName.Split(_optionsProvider.Provide().NestedPropSeparator); var initial = LambdaExpressionBuilder.Create() .AddParameter(elementType) .AccessProperty(names[0]); initial = names.Skip(1).Aggregate(initial, (builder, prop) => builder.ThenProperty(prop)); var result = initial .FinishAccess() .Build(); if (!result.IsSuccessfull) { throw new BadMemberAccessException(string.Join('\n', result.Errors)); } return(result.Result); }
public string Show() { int intPageIndex = Request["PageIndex"].ToInt32(); int intPageSize = Request["PageSize"].ToInt32(); string strField = Request["Field"].ToStr(); string strFieldValue = Request["FieldValue"].ToStr(); var listFilter = new List <Utility.Filter>(); //动态查询表达式 listFilter.Add(Utility.Filter.Add(strField, Op.Equals, strFieldValue, true)); var expTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <TaskList>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add("UID", "desc"); //分页获取数据 Page <TaskList> listTaskList = AllServices.TaskListService.GetByPage(intPageIndex, intPageSize, expTaskList, dicOrderBy); return(listTaskList.ToJson()); }
/// <summary> /// Returns the hacker news on the website. /// </summary> /// <param name="filterField">.</param> /// <param name="filterOperation">.</param> /// <param name="orderByField">.</param> /// <param name="orderByFieldDesc">.</param> /// <param name="maxResultCount">.</param> /// <returns>.</returns> public async Task <IList <HackerNewsItem> > GetHackerNewsManualCleaner(HackerNewsFieldEnum filterField, HackerNewsFilterOperationEnum filterOperation, HackerNewsFieldEnum orderByField, bool orderByFieldDesc, int maxResultCount) { IList <HackerNewsItem> hackerNewsItemList; // Initialize http client using (HackerNewsClient hackerNewsClient = new HackerNewsClient()) { // Get response from web site using (Stream hackerNewsHtmlContent = await hackerNewsClient.GetNewsAsStream()) { ManualHtmlTableParser dataManualScraping = new ManualHtmlTableParser(); hackerNewsItemList = await dataManualScraping.ScrapeHackerNewsHtmlContent(hackerNewsHtmlContent, maxResultCount); } } LambdaExpressionBuilder <HackerNewsItem> expressionBuilder = new LambdaExpressionBuilder <HackerNewsItem>(); Expression <Func <HackerNewsItem, bool> > filteringQuery = GetHackerNewsItemExpressionFilter(expressionBuilder, filterField, filterOperation); Expression <Func <HackerNewsItem, object> > sortingQuery = GetHackerNewsItemExpressionSort(expressionBuilder, orderByField, orderByFieldDesc); // DEBUG: To check the final value if (filteringQuery != null) { hackerNewsItemList = hackerNewsItemList.Where(filteringQuery.Compile()).ToList(); } if (sortingQuery != null) { if (orderByFieldDesc) { hackerNewsItemList = hackerNewsItemList.OrderByDescending(sortingQuery.Compile()).ToList(); } else { hackerNewsItemList = hackerNewsItemList.OrderBy(sortingQuery.Compile()).ToList(); } } return(hackerNewsItemList); }
public void Complex_Test() { var searchParameters = new SearchParameters(); searchParameters.Query = new QueryModel(); searchParameters.Query.Add(new Condition() { Field = "IntValue", Op = Operation.LessThan, Value = 30 }); searchParameters.Query.Add(new Condition() { Field = "StringValue", Op = Operation.Contains, Value = "山", OrGroup = "StringValue" }); searchParameters.Query.Add(new Condition <Foo>() { Field = x => x.StringValue, Op = Operation.Contains, Value = "有朋", OrGroup = "StringValue" }); var lambda = LambdaExpressionBuilder.BuildLambda <Foo>(searchParameters.Query); var where = lambda.Compile(); var result = _fooList.Where(where); }
public string GetListByPage() { int intPageIndex = Request["PageIndex"].ToInt(1); int intPageSize = Request["PageSize"].ToInt(10); string strTaskName = Request["TaskName"].ToStr(); string strSort = Request["Sort"].ToStr(" "); string strOrder = Request["Order"].ToStr("desc"); var listFilter = new List <Utility.Filter>(); //动态查询表达式 listFilter.Add(Utility.Filter.Add("TaskName", Op.Contains, strTaskName, true)); var exp = LambdaExpressionBuilder.GetExpressionByAndAlso <Task>(listFilter); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add(strSort, strOrder); //分页获取数据 Page <Models.Task> listTaskModel = AllServices.TaskService.GetByPage(intPageIndex, intPageSize, exp, dicOrderBy); return(listTaskModel.ToJson()); }
public RuleExpressionBuilderFactory(ReSettings reSettings, RuleExpressionParser expressionParser) { _reSettings = reSettings; _lambdaExpressionBuilder = new LambdaExpressionBuilder(_reSettings, expressionParser); }
/// <summary> /// 根据传入的名称模糊查询满足模糊的所有ID进行返回 /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public virtual Task <List <NameByIdDto> > FindIdListByNameContains(IdByNameContainsParams request, ServerCallContext context) { return(Task.Run(() => { FilterCollection _filterCollection = new FilterCollection(); Type type = typeof(IdByNameContainsParams); Type tType = typeof(M); PropertyInfo propertyInfo; for (int i = 0; i < request.queryWheres.Count; i++) { var fieldName = type.GetProperty($"MappingDbField{i + 1}").GetValue(request); if (fieldName != null) { if (!string.IsNullOrEmpty(request.queryWheres[i].NameVal)) { propertyInfo = tType.GetProperty(fieldName.ToString()); List <Filter> filter = new List <Filter> { new Filter { PropertyName = fieldName.ToString(), Value = request.queryWheres[i].NameVal.ChangeTypeExtend(propertyInfo) } }; if (request.queryWheres[i].IsLike) { filter[0].Operation = AttributeModel.ExpressionOptions.Contains; } else { filter[0].Operation = AttributeModel.ExpressionOptions.Equals; } _filterCollection.Add(filter); } else if (request.queryWheres[i].NameValIntList != null) { List <Filter> filter = new List <Filter> { new Filter { PropertyName = fieldName.ToString(), Value = request.queryWheres[i].NameValIntList, Operation = AttributeModel.ExpressionOptions.ContainsList } }; _filterCollection.Add(filter); } } } List <NameByIdDto> mList = baseService().FindAll( LambdaSelectBuilder.BuildSelect <M, NameByIdDto>(new Dictionary <string, string> { { "NAME1", request.MappingDbField1 }, { "NAME2", request.MappingDbField2 }, { "NAME3", request.MappingDbField3 }, { "NAME4", request.MappingDbField4 }, { "NAME5", request.MappingDbField5 }, { "NAME6", request.MappingDbField6 }, { "NAME7", request.MappingDbField7 } }) , LambdaExpressionBuilder.GetExpression <M>(_filterCollection)).Result; return mList; })); }
/// <summary> /// 分页展示图片 /// </summary> /// <returns></returns> public string Show() { int intPageIndex = Request["PageIndex"].ToInt32(); int intPageSize = Request["PageSize"].ToInt32(); int intState = Request["State"].ToInt32(); string strQueryList = Request["QueryList"].ToStr(); string strOrder = Request["Order"].ToStr() == string.Empty ? "asc" : Request["Order"].ToStr(); string strCond = Request["Cond"].ToStr() == string.Empty ? "DocumentName" : Request["Cond"].ToStr();//默认排序 姓名 a-z递增 List <DataModel> listDataModel = JsonHelper.ToListDataModel(strQueryList); var listFilter1 = new List <Utility.Filter>(); var listFilter2 = new List <Utility.Filter>(); var listFilter3 = new List <Utility.Filter>(); foreach (DataModel dataModel in listDataModel) { string strField = dataModel["Field"].ToStr(); string strOperation = dataModel["Operation"].ToStr(); string strFieldValue = dataModel["FieldValue"].ToStr(); if (!Enum.IsDefined(typeof(Op), strOperation)) //第二个参数也可以传入intValue { strOperation = Op.Equals.ToString(); //没有 } Op op = (Op)Enum.Parse(typeof(Op), strOperation); if (strField == "Tag") { listFilter2.Add(Utility.Filter.Add(strField, op, strFieldValue, true)); } else if (strField == "FolderUID") { listFilter3.Add(Utility.Filter.Add(strField, op, strFieldValue, true)); } else if (strField == "CreateTime") { listFilter1.Add(Utility.Filter.Add(strField, op, Convert.ToDateTime(strFieldValue), true)); } else { listFilter1.Add(Utility.Filter.Add(strField, op, strFieldValue, true)); } } //,string strTag,DateTime dateBeginTime,DateTime dateEndTime //动态查询表达式 if (intState <= 10) { listFilter1.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Enable), true)); } else { listFilter1.Add(Utility.Filter.Add("State", Op.Equals, Convert.ToString((int)ItemState.Disable), true)); } var expTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <Document>(listFilter1); var expTagTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <DocumentTag>(listFilter2); var expDocumentFolderTaskList = LambdaExpressionBuilder.GetExpressionByAndAlso <DocumentFolder>(listFilter3); //排序所需字典 Dictionary <string, string> dicOrderBy = new Dictionary <string, string>(); dicOrderBy.Add(strCond, strOrder); //分页获取数据 Page <Document> listDocumentList = AllServices.DocumentService.GetByPage(intPageIndex, intPageSize, expTaskList, dicOrderBy, expTagTaskList, expDocumentFolderTaskList); return(CommonResult.Instance(1, null, listDocumentList).ToJson()); }
/// <summary> /// 数据有效查询条件生成 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="V"></typeparam> /// <param name="queryable"></param> /// <param name="queryParams"></param> /// <returns></returns> public static IQueryable <T> AvailWhereJoinBuild <T>(IQueryable <T> queryable) { Type _MainType = typeof(T); FilterCollection _filterCollection = new FilterCollection(); AvailRemarkAttribute[] availList = (AvailRemarkAttribute[])_MainType.GetCustomAttributes <AvailRemarkAttribute>(); if (availList == null || availList.Length == 0) { throw new Exception("未找到校验数据有效性的特性标识 [AvailRemarkAttribute] !"); } else { availList.ToList().ForEach(a => { //校验字段名称是否存在 if (_MainType.GetProperty(a._bindProperName) == null) { throw new Exception($"未在 [{_MainType.Name}] 实体中找到需要做数据有效性校验的字段 [{a._bindProperName}] !"); } else { //同一个List<Filter>中的Filter将采用 OR List <Filter> filters = new List <Filter>(); if (a._avaliType == AvaliType.Equals) { filters.Add(new Filter() { PropertyName = a._bindProperName, Value = a._bindProperValue, Operation = ExpressionOptions.Equals }); } else if (a._avaliType == AvaliType.ContainsList) { filters.Add(new Filter() { PropertyName = a._bindProperName, Value = ((string[])a._bindProperValue).ToList(), Operation = ExpressionOptions.ContainsList }); } else if (a._avaliType == AvaliType.StartDate) { filters.Add(new Filter() { PropertyName = a._bindProperName, Value = Convert.ToDateTime(a._bindProperValue), Operation = ExpressionOptions.LessThanOrEqual }); } else if (a._avaliType == AvaliType.EndDate) { filters.Add(new Filter() { PropertyName = a._bindProperName, Value = Convert.ToDateTime(a._bindProperValue), Operation = ExpressionOptions.GreaterThanOrEqual }); } if (a._isContainsNull) { filters.Add(new Filter() { PropertyName = a._bindProperName, Value = null, Operation = ExpressionOptions.Equals }); } _filterCollection.Add(filters); } }); } //生成条件Lambda表达树 if (_filterCollection.Count > 0) { queryable = queryable.Where(LambdaExpressionBuilder.GetExpression <T>(_filterCollection)); } return(queryable); }
/// <summary> /// 自动校验 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tModel"></param> /// <param name="funcValid"></param> /// <returns></returns> public static string ValidWhereJoinBuild <T>(T tModel, Func <Expression <Func <T, bool> >, int> funcValid) { Type type = typeof(T); IdentityGroupUniqueAttribute _Igua = type.GetCustomAttribute <IdentityGroupUniqueAttribute>(); if (_Igua == null) { return("1"); } var IdVal = type.GetProperty("ID").GetValue(tModel); List <Filter> IdFilterList = new List <Filter> { new Filter { Operation = ExpressionOptions.NotEquals, PropertyName = "ID", Value = IdVal } }; string[] singGroupArray = _Igua.groupUniqueArray.Split("|"); FilterCollection _filterCollection = new FilterCollection(); for (int i = 0; i < singGroupArray.Length; i++) { _filterCollection.Clear(); //默认加上 ID!=ID _filterCollection.Add(IdFilterList); //一组 string[] singArray = singGroupArray[i].Split(","); //第0个是消息编码 for (int j = 1; j < singArray.Length; j++) { bool IsNullIf = false; string propertyName = singArray[j]; if (propertyName.IndexOf("[NULL]") >= 0) { propertyName = propertyName.Replace("[NULL]", ""); IsNullIf = true; } var propertyVal = type.GetProperty(propertyName).GetValue(tModel); if (IsNullIf) { if (propertyVal != null) { WhereAppend(); } } else { WhereAppend(); } void WhereAppend() { _filterCollection.Add(new List <Filter> { new Filter { Operation = ExpressionOptions.Equals, PropertyName = propertyName, Value = propertyVal } }); } } //只有ID!=ID if (_filterCollection.Count == 1) { return("1"); } int validCount = funcValid(LambdaExpressionBuilder.GetExpression <T>(_filterCollection)); if (validCount > 0) { return(singArray[0]); } } return("1"); }
/// <summary> /// 自动生成查询条件 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="V"></typeparam> /// <param name="queryable"></param> /// <param name="queryParams"></param> /// <returns></returns> public static IQueryable <T> QueryWhereJoinBuild <T, V>(IQueryable <T> queryable, V queryParams) { Type _MainType = typeof(T); Type _QueryType = queryParams.GetType(); FilterCollection _filterCollection = new FilterCollection(); PropertyInfo[] _QueryPropertys = _QueryType.GetProperties(); _QueryPropertys.Where(q => !q.Name.Contains("IS_LIKE_") && q.GetCustomAttribute <NotQueryParamsBuildOptionsAttribute>() == null).ToList().ForEach(p => { string queryVal = Convert.ToString(p.GetValue(queryParams)); if (!string.IsNullOrEmpty(queryVal)) { QueryParamsBuildOptionsAttribute _Qpboa = p.GetCustomAttribute <QueryParamsBuildOptionsAttribute>(); if (_Qpboa == null) { _Qpboa = new QueryParamsBuildOptionsAttribute(ExpressionOptions.Equals); } //DB字段名称 默认使用属性名称 string pName = p.Name; PageQueryFieldMappingAttribute _Pqfma = p.GetCustomAttribute <PageQueryFieldMappingAttribute>(); if (_Pqfma != null) { pName = _Pqfma.EntityFieldName; } List <Filter> filters = new List <Filter> { //同一个List<Filter>中的Filter将采用 OR new Filter() { PropertyName = pName, Value = p.GetValue(queryParams) } }; if (_Qpboa._Options == ExpressionOptions.Normal) { //不用特性指定的实体名称 就对应使用查询条件字段名称 if (Convert.ToBoolean(_QueryType.GetProperty("IS_LIKE_" + p.Name).GetValue(queryParams))) { //模糊查询 filters[0].Operation = ExpressionOptions.Contains; } else { //全词查询 filters[0].Operation = ExpressionOptions.Equals; } } else { filters[0].Operation = _Qpboa._Options; } _filterCollection.Add(filters); } }); //生成条件Lambda表达树 if (_filterCollection.Count > 0) { queryable = queryable.Where(LambdaExpressionBuilder.GetExpression <T>(_filterCollection)); } //是否自动根据有效标识进行有效过滤 默认查询全部 bool IS_QUERY_AVAIL = false; PropertyInfo availProperty = _QueryType.GetProperty("IS_QUERY_AVAIL"); if (availProperty != null) { IS_QUERY_AVAIL = (bool)availProperty.GetValue(queryParams); if (IS_QUERY_AVAIL) { return(AvailWhereJoinBuild(queryable)); } } return(queryable); }
/// <summary> /// The GetHackerNewsItemExpressionFilter. /// </summary> /// <param name="expressionBuilder">The expressionBuilder<see cref="LambdaExpressionBuilder{HackerNewsItem}"/>.</param> /// <param name="filterField">The filterField<see cref="HackerNewsFieldEnum"/>.</param> /// <param name="filterOperation">The filterOperation<see cref="HackerNewsFilterOperationEnum"/>.</param> /// <returns>The <see cref="Expression{Func{HackerNewsItem, bool}}"/>.</returns> private Expression <Func <HackerNewsItem, bool> > GetHackerNewsItemExpressionFilter(LambdaExpressionBuilder <HackerNewsItem> expressionBuilder, HackerNewsFieldEnum filterField, HackerNewsFilterOperationEnum filterOperation) { IList <QueryFilter> queryFilterList = new List <QueryFilter>(); var queryFilter = new QueryFilter { PropertyPath = filterField.GetDescription(), }; if (filterOperation == HackerNewsFilterOperationEnum.MoreThanFiveWords) { queryFilter.Operator = LambdaExpressionBuilder.Enums.OperatorEnum.GreaterThan; queryFilter.PropertyValue = "5"; } if (filterOperation == HackerNewsFilterOperationEnum.MoreThanOrEqualToFiveWords) { queryFilter.Operator = LambdaExpressionBuilder.Enums.OperatorEnum.GreaterThanOrEqualTo; queryFilter.PropertyValue = "5"; } if (filterOperation == HackerNewsFilterOperationEnum.LessThanFiveWords) { queryFilter.Operator = LambdaExpressionBuilder.Enums.OperatorEnum.LessThan; queryFilter.PropertyValue = "5"; } if (filterOperation == HackerNewsFilterOperationEnum.LessThanOrEqualToFiveWords) { queryFilter.Operator = LambdaExpressionBuilder.Enums.OperatorEnum.LessThanOrEqualTo; queryFilter.PropertyValue = "5"; } queryFilterList.Add(queryFilter); return(expressionBuilder.BuildQueryFilteringExpression(queryFilterList)); }
/// <summary> /// The GetHackerNewsItemExpressionSort. /// </summary> /// <param name="expressionBuilder">The expressionBuilder<see cref="LambdaExpressionBuilder{HackerNewsItem}"/>.</param> /// <param name="orderByField">The orderByField<see cref="HackerNewsFieldEnum"/>.</param> /// <param name="orderByFieldDesc">The orderByFieldDesc<see cref="bool"/>.</param> /// <returns>The <see cref="Expression{Func{HackerNewsItem, object}}"/>.</returns> private Expression <Func <HackerNewsItem, object> > GetHackerNewsItemExpressionSort(LambdaExpressionBuilder <HackerNewsItem> expressionBuilder, HackerNewsFieldEnum orderByField, bool orderByFieldDesc) { QuerySort querySort = new QuerySort { PropertyPath = orderByField.GetDescription(), Desc = orderByFieldDesc }; return(expressionBuilder.BuildQuerySortingExpression(querySort)); }
private static void Main(string[] args) { LambdaExpressionBuilder <Subject> expressionBuilder = new LambdaExpressionBuilder <Subject>(); IEnumerable <Subject> foodList = new Seed().GetSubjectList(); IList <QueryFilter> queryFilterList = new List <QueryFilter> { new QueryFilter { PropertyPath = "Id", Operator = OperatorEnum.EqualTo, PropertyValue = "0" } }; QuerySort querySort = new QuerySort { PropertyPath = "Id", Desc = false }; Expression <Func <Subject, bool> > filteringQuery = expressionBuilder.BuildQueryFilteringExpression(queryFilterList); Expression <Func <Subject, object> > sortingQuery = expressionBuilder.BuildQuerySortingExpression(querySort); List <Subject> result = foodList.Where(filteringQuery.Compile()) .AsQueryable() .OrderBy(sortingQuery) .ToList(); Console.WriteLine("------------------"); Console.WriteLine("---- QUERY -----"); Console.WriteLine("------------------"); Console.WriteLine(expressionBuilder.ToString(filteringQuery)); Console.WriteLine("------------------"); Console.WriteLine("---- SORT ------"); Console.WriteLine("------------------"); Console.WriteLine(expressionBuilder.ToString(sortingQuery)); Console.WriteLine("------------------"); Console.WriteLine("---- RESULT ----"); Console.WriteLine("------------------"); for (int i = 0; i < result.Count; i++) { Console.WriteLine(result[i].ToString()); } queryFilterList = new List <QueryFilter> { new QueryFilter { PropertyPath = "Teacher.Name", Operator = OperatorEnum.Contains, PropertyValue = "a" }, }; querySort = new QuerySort { PropertyPath = "teacher.name", Desc = false }; filteringQuery = expressionBuilder.BuildQueryFilteringExpression(queryFilterList); sortingQuery = expressionBuilder.BuildQuerySortingExpression(querySort); result = foodList.Where(filteringQuery.Compile()) .AsQueryable() .OrderBy(sortingQuery) .ToList(); Console.WriteLine("------------------"); Console.WriteLine("---- QUERY -----"); Console.WriteLine("------------------"); Console.WriteLine(expressionBuilder.ToString(filteringQuery)); Console.WriteLine("------------------"); Console.WriteLine("---- SORT ------"); Console.WriteLine("------------------"); Console.WriteLine(expressionBuilder.ToString(sortingQuery)); Console.WriteLine("------------------"); Console.WriteLine("---- RESULT ----"); Console.WriteLine("------------------"); for (int i = 0; i < result.Count; i++) { Console.WriteLine(result[i].ToString()); } Console.ReadLine(); }