w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Convert Expression> to Expression>>
Quite simple, really. The trick is to play with the body of the source expression, while reusing its parameters. public static Expression<Func<T, V?>> ToNullableExpression<T, V> (this Expression<Func<T, V>> source) where V : struct { if(source == null) throw new ArgumentNullException("source"); var body = Expression.Convert(source.Body, typeof(V?)); var parameters = source.Parameters; return Expression.Lambda<Func<T, V?>>(body, parameters); }

Categories : C#

How can I do a Func>> dynamic?
You need to use the Expression.Constant method instead of the Expression.ArrayIndex, because you will not be able to pass to your expression array with the key values ​​using the FirstOrDefault method. private static LambdaExpression CreateKeyExpression(Type C1Type, object[] parameters) { var instanceParameter = Expression.Parameter(C1Type); PropertyInfo[] objectKeys = C1Type.GetKeyProperties().ToArray(); var expr = Expression.Equal(Expression.Property(instanceParameter, objectKeys[0]), Expression.Constant(parameters[0], objectKeys[0].PropertyType)); for (int i = 1; i < objectKeys.Length; i++) { expr = Expression.AndAlso(expr, Expression.Equal( Expression.Property(instanceParameter, objectKeys[i]), Expression.Constant(p

Categories : C#

Converting from Expression> to Expression>
Because of the propertyType == typeof(bool) test, it should already be the right thing - you just need to convince the compiler that your intentions are honest. In this case, via: var typedExpression = (System.Linq.Expressions.Expression<System.Func<TModel,bool>>)(object)expression; return htmlHelper.CheckBoxFor(typedExpression);

Categories : C#

Convert Expression> to Expression>
Why don't you just change your method to be: T GetSingle(IRepository<T> repository, Expression<Func<TSource, Boolean>> predicate) { return repository.GetAll().Single(predicate); } so instead of this: GetSingle(myRepository, (a,b) => a.Id == b.Id, myEntity); you should be able to do this: GetSingle(myRepository, a => a.Id == myEntity.Id);

Categories : C#

Getting from Func + T instance to Expression>
T instance = GetSomeT(); Predicate<T> MyPredicate = x => comparer(x, instance); TRepository.GetAll().Where(MyPredicate); Taking in account the comment gave below, here is how you make a Expression<Func<T, bool>> T instance = GetSomeT(); Expression<Func<T, bool>> Exp = x => comparer(x, instance); TRepository.GetAll().Where(Exp); That's exactly the same, just with different var type. In short you can just: TRepository.GetAll().Where(x => comparer(x, instance));

Categories : C#

I can't access property on my object via Expression.Property unless the type of the fed expression is strongly-typed
Inner is declared as an object. And clearly, an object doesn't contain a Value property. You need to "convert" that expression to the expected type before you attempt to access that property. This is equivalent to adding a cast to the expression. Func<OuterClass, object> e = Expression.Lambda<Func<OuterClass, object>>( Expression.Property( Expression.Convert(Expression.Property(p, "Inner"), typeof(InnerClass)), "Value" ), p ).Compile();

Categories : C#

Func parameter in LINQ expression
If you want to work on a IQueryable<T>, your argument must be an Expression<Func<T, int>>, not a Func<T, int>. Func<T, int> will work with an IEnumerable<T>. Where extensions methods has the same name for IQueryable<T> and IEnumerable<T>, but not the same arguments... (by the way you could write repository.Items.FirstOrDefault(x => keyExtractor(x) == id);

Categories : C#

Expression> method argument
You'll need to declare T as a generic type parameter on the method: public string GetExpressionString<T>(Expression<Func<T, bool>> exp) where T: class { return exp.Body.ToString(); } // call like this GetExpressionString<string>(s => false); GetExpressionString((Expression<Func<string, bool>>)(s => false)); Or on the parent class: public class MyClass<T> where T: class { public string GetExpressionString(Expression<Func<T, bool>> exp) { return exp.Body.ToString(); } } // call like this var myInstance = new MyClass<string>(); myInstance.GetExpressionString(s => false); Further Reading: Generic Methods (C# Programming Guide)

Categories : C#

How to convert IQueryable to Expression>?
Any reason you don't just do the following: public IQueryable<Event> GetBySearch(EventFilter search) { IQueryable<Event> query = this.Context.Events.AsQueryable(); if (search.CategoryId != 0) { query = query.Where(x => x.CategoryId == search.CategoryId); } if (search.SubCategoryId != 0) { query = query.Where(x => x.SubCategoryId == search.SubCategoryId); } return query; } As Florian said in the comment, returning IQueryables is to be avoided (when possible). The easy solution is to return a list instead: public List<Event> GetBySearch(EventFilter search) { IQueryable<Event> query = this.Context.Events.AsQueryable(); if (search.CategoryId != 0) { query = query.Where(x => x.CategoryId

Categories : C#

Entity framework calculated field by Expression>
No, this is not currently possible. The closest I've seen is using LinqKit to build reusable "selectors" that are too lengthy/common to want to repeat in code. It ends up looking like: var fullNameSelector = MyExpressions.FullNameSelector; var query = from o in ctx.Orders.AsExpandable() select new { Id = o.Id, FullName = fullNameSelector.Invoke(o) };

Categories : C#

Entity Framework Filter "Expression>"
Why it works in one case and not in the adder? Because EF doesn't really "know" about your Filter method. It has no understanding of what it's meant to do, so it doesn't know how to translate it into SQL. Compare that with Where etc, which it does understand. The version where you call it directly on the initial table works because that way you don't end up with an expression tree containing a call to Filter - it just calls Filter directly, which in turn does build up a query... but one which EF understands. I'd be very surprised if you could work out a way of getting your Filter method to work within an EF query... but you've already said that using Where works anyway, so why use Filter at all? I'd use the Where version - or better yet, use the Any overload which takes a predicate:

Categories : C#

How can I verify whether a Func<> property has been initialized?
ClassA clsA = new ClassA(); if (clsA.MyProperty == null) MessageBox.Show("IsNull"); clsA.MyProperty = new Func<string, bool>(x => x.Equals("1")); MessageBox.Show(clsA.MyProperty == null ? "IsNull" : "IsNotNull"); this works very good

Categories : C#

Invoke a method using reflection by passing an Expression>
The problem is that Expression<T> is invariant, so even if you have a type T which can be assigned to type U, that doesn't mean that Expression<T> can be assigned to Expression<U>. In your case, T is Func<CLI, IList<Grouping>> and U is Func<CLLI, object>. I think the only solution is to create a function to wrap a given expression in an Expression<Func<T, object>> which delegates to the inner expression and casts the result to object: public static Expression<Func<T, object>> ConvertResult<T, TOut>(Expression<Func<T, TOut>> expr) { var paramExpr = Expression.Parameter(typeof(T)); var invokeExpr = Expression.Invoke(expr, paramExpr); var castExpr = Expression.Convert(invokeExpr, typeof(object));

Categories : C#

Cast lambda expression to Func, IDisposable>
As @Patryk notes, this is basically the same as asking: "why is this allowed to say that it returns int, when it doesn't?": int SomeMethod() { while (true) { } } And by answer; it doesn't, in any code path, return something different (another type, or void) - so sure, why not; the compiler can represent that as a method that returns int.

Categories : C#

Convert async lambda expression to delegate type System.Func?
No can do. When someone expects a Func<T> f you can assume it will be invoked with something like result = f() - i.e., it does not know about async behavior. If you cheat it by using .Result like you have - it will deadlock on UI thread because it wants to schedule the code after await (in _Fetch) on the UI thread, but you have already blocked it with .Result. Async lambda can be passed to Action since it has no return value - or to Func<Task> or Func<Task<T>>. Looking at your case, the GetOrCreateObject appears to be calling GetOrFetchObject. One of the GetOrFetchObject overloads accepts a Func<Task<T>>. You can try calling that method with your async lambda and see if it helps.

Categories : C#

Why does Linq (Expression>) generate incorrect Where clauses in a generic class?
I haven't tested Select method I use SelectParam and everything works perfectly. Below I put my generic repository pattern with OrmLite(Maybe it will help you) - It works great with Specification pattern. public class GenericRepository<T> : IRepository<T> where T : class, new() { private readonly IDbConnectionFactory dbConnectionFactory; public GenericRepository(IDbConnectionFactory dbConnectionFactory) { this.dbConnectionFactory = dbConnectionFactory; } public IEnumerable<T> FindAll() { return dbConnectionFactory.OpenDbConnection().Select<T>(); } public IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate) { return dbConnectionFactory.OpenDbConnection().SelectParam<T>(p

Categories : Misc

Warning: resolving Func by linking to Func@##
You need to supply either --enable-stdcall-fixup to the linker (which fixes up the problem automatically). When using with gcc or g++, this means -Wl,--enable-stdcall-fixup. For details of these options, check section 2.1.1 of Gnu Linker options.

Categories : C++

Spring MVC/Hibernate - NullValueInNestedPathException, Invalid property, value of nested property is null?
I found out what was wrong: It seems that I set the default value of the column for the new property to null! I hope that others that are getting this same error try this solution out. -__-! Thanks to drurenia taking some interest! :D

Categories : Hibernate

WPF binding update notification for nested property when parent property changes
I'm not an WPF expert, but I think it's because you've chosen the wrong path. <TextBlock Text="{Binding Path=MyCarProperty, Value=Manufacturer}" /> update: <TextBlock Text="{Binding Source=MyCarProperty, Path=Manufacturer}" />

Categories : C#

Convert Func to Func
Why not pass it in public Cv3AddressDao ReadSingle<TEntity>(Expression<Func<TEntity, bool>> predicate) { // ... } ... var dao = new MyDao(); var addr = dao.ReadSingle<MyEntity>(x => x.SiteId == 1);

Categories : C#

Passing Func to method where the func needs parameters from inside method
Change your parameter Funcs to take 2 input parameters: rec and sec. new Func<StationEquality, StationEquality, bool>((rec, sec) => ... ) Then inside your method, don't call the predicate directly. Instead, wrap it in another predicate passing the supplied rec parameter along with your sec parameter. For example: .Where((rec) => ascendingPredicate(rec, sec)) I have not compiled nor tested this.

Categories : C#

Get property by name to use in Expression
typeof(Employee).GetProperty(propertyName) to get a PropertyInfo object. To get the value of the property of that specific instance, use: public BaseInfo GetPropertyByName(Employee employee, string propertyName) { var propInfo = typeof(Employee).GetProperty(propertyName); return propInfo.GetValue(employee) as BaseInfo; } However, this will return null if the property you request is of a type other than BaseInfo.

Categories : C#

Nested switch with different expression types
Your problem is a scoping problem: you define arith inside an "if" and then you try to use it outside the if statement. Whenever you open curly braces you open a new frame on the stack (just like calling a method), and when this frame is done executing - the frame is removed from the stack including all the local parameters that were defined there. Changing: if (Source == 1) { String[] arith = {"Add","Sub"}; codePos = Arrays.binarySearch(arith, 0, arith.length, Target); } to: String[] arith = {"Add","Sub"}; if (Source == 1) { codePos = Arrays.binarySearch(arith, 0, arith.length, Target); } should solve your issue.

Categories : Java

How do I Convert Func to Func?
create a new function that takes the dynamic object, casts it to the object that you need it to be, and then passes that value to the more specific function that you have: Format = dyn => format((T)dyn);

Categories : C#

LINQ expression instead of nested foreach loop
Console.WriteLine(String.Join(Environment.NewLine, pro.TokenList.SelectMany(s => s) )); Or, Console.WriteLine(String.Join(Environment.NewLine, from arr in pro.TokenList from s in arr select s ));

Categories : C#

remove nested element using regular expression
Unfortunately, one of the known limitations of regex is that it does not handle nesting You can and should use whatever XML parser is available in whatever language you're using. If you have a very specifically formed piece of XML, and a very specific goal, than it is possible to use regex to perform some operations on it, but once you try to apply your regex to a non-specific piece of xml, it will be unable to handle it.

Categories : C#

Nested switch with different expression types: ArrayIndexOutOfBoundsException -4
Arrays.binarySearch returns a negative number if it can't find the value. Also, to use a binary search, the array has to be sorted, which it's not, which is probably causing your error. Declare your array like so: String[] Mult = {"Division", "Modulas", "Multiplication" };

Categories : Java

Nested Select in LINQ with Lambda Expression
Any returns a bool, not a list of values. If you want a list of Newsflash ID's, you would use Newsflash.Select(x => x.Id) To get your list of messages that have a newsflash, you should use: var messages = (from m in Messages join n in Newsflash on m.Id equals n.Id select m).ToList(); This will join messages to your newsflash based on the Id for each, and then select the Message object that matches. alternative lamba syntax: var messages = Messages.Join(Newsflash, x => x.Id, y => y.Id, (x, y) => new { Message = x }).ToList();

Categories : Linq

Is nested grouping allowed in Expression Language?
See EL 2.2 Specification 1.12 Parantheses: "Parentheses can be used to change precedence, as in: ${(a*(b+c))}". So the answer is: Yes, nested grouping is allowed. But besides reading the spec or asking question on SO, there is another way to find out such things... trying.

Categories : JSF

Get Dependecy Property from Binding expression
Yes from looking at the Documentation you can find a property on the BindingExpression object called TargetProperty which returns a DependencyProperty ( like TextBox.TextProperty).

Categories : C#

Get Function Property of a class using Expression
public static void SomeMethod<TProperty>(Expression<Func<TProperty>> property) { var propertyName = property.Name; // Do something, } public static void SomeMethod<TProperty>(object sender, PropertyInfo property) { SomeMethod(Expression.Lambda<Func<TProperty>>(Expression.Property(Expression.Constant(sender), property))); } public static MethodInfo someMethod = typeof(TypeContainingSomeMethod).GetMethod("SomeMethod", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(object), typeof(PropertyInfo) }, null); static void EventHandler(object sender, PropertyChangedEventArgs e) { var propertyInfo = sender.GetType().GetProperty(e.PropertyName); someMethod.MakeGenericMethod(propertyInfo.PropertyType).Invoke(null, new[] { sende

Categories : C#

Creating an expression from the string of a property name?
Something like this: public static IQueryable<T> FilterObjectSet<T>(IQueryable<T> inputQuery, Rule rule) where T : class { var par = Expression.Parameter(typeof(T)); var prop = Expression.PropertyOrField(par, rule.field); var propType = prop.Member.MemberType == System.Reflection.MemberTypes.Field ? ((FieldInfo)prop.Member).FieldType : ((PropertyInfo)prop.Member).PropertyType); // I convert the data that is a string to the "correct" type here object data2 = Convert.ChangeType(rule.data, propType, CultureInfo.InvariantCulture); var eq = Expression.Equal(prop,

Categories : C#

LINQ Expression of the Reference Property
You need to do this one property at a time: private static Expression<Func<Menu, string>> GetGroupKey(string property) { var parameter = Expression.Parameter(typeof(Menu)); Expression body = null; foreach(var propertyName in property.Split('.')) { Expression instance = body; if(body == null) instance = parameter; body = Expression.Property(instance, propertyName); } return Expression.Lambda<Func<Menu, string>>(body, parameter); } This answer extends the GetGroupKey method I showed you in my answer to your previous question.

Categories : C#

Regex expression to search upto nested level
You could get this result using (?<={)[^{}]*(?=}), assuming a language other than JavaScript. In C#, for example, that's result = Regex.Match(str, @"(?<={)[^{}]*(?=})").Value; If you're using JavaScript, use {([^{}]*)} and access $1 for the match result: var myregexp = /{([^{}]*)}/; var match = myregexp.exec(subject); if (match != null) { result = match[1]; }

Categories : C#

Turn a property name as a string into a Linq Expression
Now that you've declared your intent for this in the comments, I believe that the accepted answer here is what you're looking for. Even if it's not doing exactly what you're looking for, these lines can carry over: // TODO: Get 'type' from the property you want. Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); You could return LambdaExpression, or just use the extension methods found in that answer, or use DynamicLinq. I guess the moral of the story (as it often is) is that its probably been done already :).

Categories : C#

Create Generic Expression from string property name
You kinda need to use the correct generic overload - which used to mean you had to use MakeGenericMethod; however, you can also use dynamic to avoid the need to use MakeGenericMethod here, for example (in this case via Where, but the important point is how it works): IQueryable<Foo> source = new[] { new Foo { Bar = 123 } }.AsQueryable(); Expression<Func<Foo,bool>> typed = x=>x.Bar == 123; LambdaExpression untyped = typed; IQueryable<Foo> filtered = Queryable.Where(source, (dynamic)untyped); Note: you can't use extension methods here - hence why you need to use Queryable.*. For an OrderBy example using your code: var parameter = Expression.Parameter(typeof(Foo)); var memberExpression = Expression.Property(parameter, "Bar"); var lambdaExpression = Expression

Categories : C#

Use LINQ expression to Update Property of object
Not sure what exactly you mean saying "dynamically" but i suppose the approach with lambdas does not fit you: static void Main(string[] args) { User user = new User { ID = 5, Name = "Test" }; SetNewValue(user, u => u.Name, s => s.StartsWith("T"), s => s + "123"); } static void SetNewValue<TObject, TProperty>(TObject obj, Func<TObject, TProperty> propertyGetter, Func<TProperty, bool> condition, Func<TProperty, TProperty> modifier) { TProperty property = propertyGetter(obj); if (condition(property)) { TProperty newValue = modifier(property); //set via reflection } } So I would recommend you using Expression trees which allow you to build any runtime construction you like, for par

Categories : C#

Is there an expression to downcast and simultaneously access a property in F#?
Your initial guess is correct, this code works: type Fruit() = member me.Test() = printfn "Test" type Banana() = inherit Fruit() member me.Peel() = printfn "Peeling !" let f = new Banana() :> Fruit (f :?> Banana).Peel() You are not showing how did you define those types, probably you have something wrong there. Also keep in mind that in F# you have to be explicit to upcast. In your example your f object is already a Banana, nothing in your code upcast it to a Fruit.

Categories : F#

How do I pass a property expression back to the controller?
As far as I know you can't pass complex objects via URL. You can pass for example string with name of property. However if you want to just sort table maybe you should think about another approach to this problem. Check this http://www.kryogenix.org/code/browser/sorttable/ . It allows you to simply sort your table by clicking on headers.

Categories : C#

Lambda expression to retrieve property which can be null
You can project results to avoid exception: var balance = td.Where(x => !String.IsNullOrEmpty(x.BALANCE_MU)) .Select(x => x.BALANCE_MU) // select property here .FirstOrDefault(); BTW default value for string is not empty string - it is null. If you want to have empty string, then as @newStackExchangeInstance suggested, you can use coalescing operator: balance ?? "". One more update. You can use oveloaded FirstOrDefault method if you will do projection before filtering: var balance = td.Select(x => x.BALANCE_MU) .FirstOrDefault(b => !String.IsNullOrEmpty(b)) ?? "";

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.