public IQueryable <T> Filter <Key>(System.Linq.Expressions.Expression <Func <T, Key> > sortingSelector, System.Linq.Expressions.Expression <Func <T, bool> > filter, out int total, SortingOrders sortby = SortingOrders.Asc, int index = 0, int size = 50) { var entities = All(); var query = sortby == SortingOrders.Asc ? entities.OrderBy(sortingSelector.Compile()).Where(filter.Compile()) : entities.OrderByDescending(sortingSelector.Compile()).Where(filter.Compile()); total = query.Count(); var skipCount = index * size; return(skipCount > 0 ? query.Skip(skipCount).Take(size).AsQueryable <T>() : query.Take(size).AsQueryable <T>()); }
public IEnumerable <T> WhereQ <T>(System.Linq.Expressions.Expression <System.Func <T, bool> > predicate) where T : IThing { if (typeof(T).GetInterface(typeof(ILink).FullName) != null) { return(edges.OfType <T>().Where(predicate.Compile())); } else { return(items.OfType <T>().Where(predicate.Compile())); } }
public override IList <TModelType> FindBy <TKey>(System.Linq.Expressions.Expression <Func <TModelType, bool> > query, System.Linq.Expressions.Expression <Func <TModelType, TKey> > order, int pageIndex, int pageCount, OrderType orderType, out int rowCount) { rowCount = this.Count(query); if (orderType == OrderType.ASC || orderType == OrderType.Default) { return(this.tempContext.Persistence.Query(query.Compile()).OrderBy(order.Compile()).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList()); } else { return(this.tempContext.Persistence.Query(query.Compile()).OrderByDescending(order.Compile()).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList()); } }
private void TitleContext_OnClickEvent(System.Linq.Expressions.Expression <Func <TModel, object> > valueExpression) { if (orderType == OrderType.None || orderType == OrderType.Descending) { Items = Items.OrderBy(valueExpression.Compile()).ToList(); orderType = OrderType.Ascending; } else { Items = Items.OrderByDescending(valueExpression.Compile()).ToList(); orderType = OrderType.Descending; } StateHasChanged(); }
public override void Delete(System.Linq.Expressions.Expression <Func <T, bool> > filter) { foreach (T item in CurrentList.Where(filter.Compile())) { CurrentList.Remove(item); } }
// i => i < 5; static void Example1() { // <Snippet1> // Lambda expression as executable code. Func <int, bool> deleg = i => i < 5; // Invoke the delegate and display the output. Console.WriteLine("deleg(4) = {0}", deleg(4)); // Lambda expression as data in the form of an expression tree. System.Linq.Expressions.Expression <Func <int, bool> > expr = i => i < 5; // Compile the expression tree into executable code. Func <int, bool> deleg2 = expr.Compile(); // Invoke the method and print the output. Console.WriteLine("deleg2(4) = {0}", deleg2(4)); /* This code produces the following output: * * deleg(4) = True * deleg2(4) = True */ // </Snippet1> }
/// <summary> /// 重写获取分页数据方法 /// </summary> /// <param name="totalCount">总记录数</param> /// <param name="errorMsg">异常信息</param> /// <param name="permissionValidate">是否过滤权限</param> /// <param name="pageIndex">页号</param> /// <param name="pageSize">每页记录数</param> /// <param name="orderFields">排序字段</param> /// <param name="isDescs">是否降序</param> /// <param name="expression">条件表达式</param> /// <param name="whereSql">where语句</param> /// <param name="references">是否加载导航属性</param> /// <param name="connString">数据库连接字符串</param> /// <returns></returns> public override List <Sys_DbConfig> GetPageEntities(out long totalCount, out string errorMsg, bool permissionValidate = true, int pageIndex = 1, int pageSize = 10, List <string> orderFields = null, List <bool> isDescs = null, System.Linq.Expressions.Expression <Func <Sys_DbConfig, bool> > expression = null, string whereSql = null, List <string> fieldNames = null, bool references = false, string connString = null) { totalCount = 0; BaseDAL <Sys_Module> moduleDal = new BaseDAL <Sys_Module>(this.CurrUser); int dataSourceType = (int)ModuleDataSourceType.DbTable; List <Sys_Module> modules = expression == null?moduleDal.GetPageEntities(out totalCount, out errorMsg, false, pageIndex, pageSize, null, null, x => x.DataSourceType == dataSourceType) : moduleDal.GetEntities(out errorMsg, x => x.DataSourceType == dataSourceType, null, false); List <Sys_DbConfig> list = modules.Select(x => GetModuleCacheConfig(x.TableName, x.Name, x.Id)).ToList(); list = list.Where(x => x != null).ToList(); //将未添加到模块表中的模块也加进来 List <Type> modelTypes = GetAllModelTypes(); if (modelTypes == null || modelTypes.Count == 0) { return(new List <Sys_DbConfig>()); } List <string> tables = moduleDal.GetEntities(out errorMsg, x => x.TableName != null && x.TableName != string.Empty).Select(x => x.TableName).ToList(); list.AddRange(modelTypes.Where(x => !tables.Contains(x.Name)).Select(x => GetModuleCacheConfig(x.Name))); if (expression != null) { list = list.Where(expression.Compile()).ToList(); totalCount = list.Count; } //页序号 int index = pageIndex < 1 ? 0 : (pageIndex - 1); //每页记录数 int rows = pageSize < 1 ? 10 : (pageSize > 2000 ? 2000 : pageSize); list = list.Skip <Sys_DbConfig>(rows * index).Take <Sys_DbConfig>(rows).OrderByDescending(x => x.CurrPageDensity).ToList(); return(list); }
public IEnumerable <TEntity> GetByPredicate(System.Linq.Expressions.Expression <Func <TEntity, bool> > f) { Func <TEntity, bool> func = f.Compile(); IEnumerable <TEntity> answers = GetAll(); return(answers.Where(answ => func(answ))); }
public void GetCurrentClassLoggerLambdaTest() { System.Linq.Expressions.Expression <Func <ILogger> > sum = () => LogManager.GetCurrentClassLogger(); ILogger logger = sum.Compile().Invoke(); Assert.Equal("NLog.UnitTests.GetLoggerTests", logger.Name); }
/// <summary> /// 获取实体集合重写 /// </summary> /// <param name="errorMsg"></param> /// <param name="expression"></param> /// <param name="whereSql"></param> /// <param name="permissionFilter"></param> /// <param name="orderFields"></param> /// <param name="isDescs"></param> /// <param name="top"></param> /// <param name="references"></param> /// <param name="connString"></param> /// <returns></returns> public override List <Sys_CacheConfig> GetEntities(out string errorMsg, System.Linq.Expressions.Expression <Func <Sys_CacheConfig, bool> > expression = null, string whereSql = null, bool permissionFilter = true, List <string> orderFields = null, List <bool> isDescs = null, int?top = null, List <string> fieldNames = null, bool references = false, string connString = null) { BaseDAL <Sys_Module> moduleDal = new BaseDAL <Sys_Module>(this.CurrUser); int dataSourceType = (int)ModuleDataSourceType.DbTable; List <Sys_Module> modules = moduleDal.GetEntities(out errorMsg, x => x.DataSourceType == dataSourceType, null, permissionFilter); List <Sys_CacheConfig> list = modules.Select(x => GetModuleCacheConfig(x.TableName, x.Name, x.Id)).ToList(); //将未添加到模块表中的模块也加进来 List <Type> modelTypes = GetAllModelTypes(); List <string> tables = moduleDal.GetEntities(out errorMsg, x => x.TableName != null && x.TableName != string.Empty).Select(x => x.TableName).ToList(); list.AddRange(modelTypes.Where(x => !tables.Contains(x.Name)).Select(x => GetModuleCacheConfig(x.Name))); if (expression != null) { list = list.Where(expression.Compile()).ToList(); if (orderFields != null && orderFields.Count > 0) { for (int i = 0; i < orderFields.Count; i++) { string orderField = string.IsNullOrEmpty(orderFields[i]) ? "Id" : orderFields[i]; bool isdesc = isDescs != null && orderFields.Count == isDescs.Count ? isDescs[i] : true; SortComparer <Sys_CacheConfig> reverser = new SortComparer <Sys_CacheConfig>(typeof(Sys_CacheConfig), orderField, isdesc ? ReverserInfo.Direction.DESC : ReverserInfo.Direction.ASC); list.Sort(reverser); } } } return(list); }
public Func <object, object> GetFunc( Type instanceType, string memberName) { System.Reflection.PropertyInfo member = instanceType.GetProperty( memberName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); System.Linq.Expressions.ParameterExpression instance = System.Linq.Expressions.Expression.Parameter(typeof(object), "i"); System.Linq.Expressions.MemberExpression memberExp = System.Linq.Expressions.Expression.Property( System.Linq.Expressions.Expression.Convert(instance, member.DeclaringType), member); System.Linq.Expressions.Expression <Func <object, object> > getter = System.Linq.Expressions.Expression.Lambda <Func <object, object> >( System.Linq.Expressions.Expression.Convert(memberExp, typeof(object)), instance); Func <object, object> func = getter.Compile(); return(func); }
public void ComparePerformanceOfExpressionCompileVersusCreateMetaClosure() { int xx = 2; System.Linq.Expressions.Expression <Func <int, int, int> > multiplierByClosureConstantExpression = (y, z) => xx * (y + z); DateTime start; TimeSpan duration; start = DateTime.Now; for (int i = 0; i < 100000; i++) { multiplierByClosureConstantExpression.Compile(); } duration = DateTime.Now - start; Console.WriteLine(duration); Func <int, int, int, int> multiplierByClosureConstant = (x, y, z) => x * (y + z); start = DateTime.Now; for (int i = 0; i < 100000; i++) { List <object> constants = new List <object>() { 2 }; Func <int, int, int> curriedFunction = ClosedToOpenExpressionFactory.CreateMetaClosure <Func <int, int, int> >( multiplierByClosureConstant, constants); } duration = DateTime.Now - start; Console.WriteLine(duration); }
private IAccessorLambda InvokeAccessor(System.Linq.Expressions.Expression <Func <IAccessorLambda, IAccessorLambda> > invokeExpression) { accessors.All(o => { invokeExpression.Compile()(o); return(true); }); //return this.typeLambda; return(this); }
internal void AddCompilerError(Cursor cursor, System.Linq.Expressions.Expression <Func <string> > error, params object[] args) { var parts = ((System.Linq.Expressions.MemberExpression)error.Body).Member.Name.Split('_'); var errorId = parts[0]; bool?isWarning = null; switch (parts[1]) { case "ERROR": isWarning = false; break; case "WARNING": isWarning = true; break; #if DEBUG default: throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unknown error type '{0}'.", parts[1]), "error"); #endif } var errorFormat = error.Compile()(); var errorText = string.Format(CultureInfo.CurrentCulture, errorFormat, args); this.Errors.Add(new CompilerError(cursor.FileName ?? string.Empty, cursor.Line, cursor.Column, errorId, errorText) { IsWarning = isWarning ?? true }); }
/// <summary> /// Recupera a propriedade do filho compilada. /// </summary> /// <returns></returns> private Func <TLinkDataModel, int> GetChildPropertyCompiled() { if (_childProperty != null && _childPropertyCompiled == null) { _childPropertyCompiled = _childProperty.Compile(); } return(_childPropertyCompiled); }
/// <summary> /// Recupera a propriedade do filho compilada. /// </summary> /// <returns></returns> private Func <TLinkDataModel, int?> GetChildPropertyNullableCompiled() { if (_childPropertyNullable != null && _childPropertyNullableCompiled == null) { _childPropertyNullableCompiled = _childPropertyNullable.Compile(); } return(_childPropertyNullableCompiled); }
/// <summary> /// Recupera o delegate usado para recupera o identificador unico do pai. /// </summary> /// <param name="parentPropertyUid"></param> /// <returns></returns> private static Func <Colosoft.Data.IModel, int> GetParentUidGetter(System.Linq.Expressions.Expression <Func <TParentModel, int> > parentPropertyUid) { var getter = parentPropertyUid.Compile(); return(parent => { return getter((TParentModel)parent); }); }
public BlogTemplate GetBy(System.Linq.Expressions.Expression <Func <BlogTemplate, bool> > predicate, params System.Linq.Expressions.Expression <Func <BlogTemplate, object> >[] includes) { if (includes != null && includes.Any()) { return(_baseRepo.GetBy(predicate, includes)); } return(_cache.CachedBlogTemplates.SingleOrDefault(predicate.Compile())); }
/// <summary> /// Recupera a propriedade estrangeira compilada. /// </summary> /// <returns></returns> private Func <TLinkParentDataModel, int?> GetForeignPropertyNullableCompiled() { if (_foreignPropertyNullable != null && _foreignPropertyNullableCompiled == null) { _foreignPropertyNullableCompiled = _foreignPropertyNullable.Compile(); } return(_foreignPropertyNullableCompiled); }
static void Main(string[] args) { //Console.WriteLine("Hello World!"); System.Linq.Expressions.Expression <Func <int, int> > e = x => x * x; var a = e.Compile(); Console.WriteLine(a(7)); }
static void Main(string[] args) { System.Linq.Expressions.Expression <Func <int, int> > expressionTree = x => x * x; Console.WriteLine("Expression Tree:"); Console.WriteLine(expressionTree); var a = expressionTree.Compile(); Console.WriteLine("Result: " + a(8)); }
public void Register <K>(System.Linq.Expressions.Expression <Func <object, K> > msgCreationFunction) where K : IActorMessage { var func = msgCreationFunction.Compile(); var invoker = new ActorMessageInvocation <K>(func); var msgType = LocalSwitchboard.HandleValueTypeMessage(typeof(K)); _msgTypeToInstatiation.TryAdd(msgType, invoker); }
static void Main(string[] args) { Func <int, int> square = (x) => { return(x * x); }; System.Linq.Expressions.Expression <Func <int, int> > e = x => x * x; var a = e.Compile(); Console.WriteLine(a(7)); }
public void ExpressionTrees() { System.Linq.Expressions.Expression <Converter <int, double> > converter = x => Math.Pow(x, 0.5); // representing code as data Console.WriteLine(converter); Converter <int, double> compiles = converter.Compile(); }
/// <summary> /// Renders the boolean attribute, specified by the <paramref name="attributeName"/>, as long as the value of <paramref name="expression"/> evaluates to true. /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="htmlHelper"></param> /// <param name="attributeName"></param> /// <param name="expression"></param> /// <returns></returns> public static IHtmlContent RenderAttributeFor <TModel>(this Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper <TModel> htmlHelper, String attributeName, System.Linq.Expressions.Expression <Func <TModel, bool> > expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } bool shouldEmit = expression.Compile( ).Invoke(htmlHelper.ViewData.Model); return(htmlHelper.RenderAttribute(attributeName, shouldEmit)); }
public IQueryable <IEntry> GetFilteredEntries(System.Linq.Expressions.Expression <Func <IEntry, bool> > filter, bool includeDeleted = false) { var filterDelegate = filter.Compile(); var allResultsDb = includeDeleted ? _context.Get <WP8Entry>("select * from WP8Entry").ToList() : _context.Get <WP8Entry>("select* from WP8Entry where IsDeleted = 0").ToList(); var allResults = allResultsDb.Select(it => it.AsIEntry()).ToList(); var results = allResults.Where(it => filterDelegate(it)).ToList(); return(results.AsQueryable()); }
/// <summary> /// Example: using (Utils.SetUnsetMagic(() => obj.SomeProperty, "temp disable")) { DoSomething(); } /// </summary> /// <typeparam name="T"></typeparam> /// <param name="variable"></param> /// <param name="value"></param> /// <returns></returns> public static Undoer.UndoOnDispose SetUnsetMagic <T>(System.Linq.Expressions.Expression <Func <T> > variable, T value) { var oldValue = variable.Compile()(); var parameterExpression = System.Linq.Expressions.Expression.Parameter(typeof(T)); var assignExpr = System.Linq.Expressions.Expression.Assign(variable.Body, parameterExpression); var setter = System.Linq.Expressions.Expression.Lambda <Action <T> >(assignExpr, parameterExpression).Compile(); return(new Undoer(() => setter(value), () => setter(oldValue)).Do()); }
public IList <TEntity> GetAllBySort(System.Linq.Expressions.Expression <Func <TEntity, bool> > predicate, int page, int pageSize, string sortItem, int sortType) { BsonDocument sort = new BsonDocument { { sortItem, sortType } }; var result = _collection.Find(new BsonDocument()).Limit(pageSize).Sort(sort).ToListAsync().Result; return(result.AsQueryable().Where(predicate.Compile()).ToList()); }
public IQueryable <IEntry> GetFilteredEntries(System.Linq.Expressions.Expression <Func <IEntry, bool> > filter, bool includeDeleted = false) { lock (_lock) { var filterDelegate = filter.Compile(); var allResults = _context.Entries.Select(it => (IEntry)it).ToList(); var results = allResults.Where(it => includeDeleted ? filterDelegate(it) : filterDelegate(it) && (!it.IsDeleted.HasValue || (it.IsDeleted.HasValue && !it.IsDeleted.Value))).ToList(); return(results.AsQueryable()); } }
public Task <List <T> > WhereAsync(System.Linq.Expressions.Expression <Func <T, bool> > predicate) { if (!_Initialised) { NotInitialisedError(); } var result = _Table.Where(predicate.Compile()).ToList(); return(Task.FromResult(result)); }