w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Pass lambda expression to lambda argument c++11
Try using std::function: #include <functional> int main() { int x=0; int y=0; auto f = [x,y](std::function<double(int)> func) -> double {func(0); return 0.0;}; f([x](int i) -> double {return 0.0;}); }

Categories : C++

Difference between lambda expression and expression lambda
Yes there is - or I should probably say that one defines the other. A lambda expression allows you to assign simple anonymous functions. An expression lambda is a type of lambda that has an expression to the right of the lambda operator. The other type of lambda expression is a statement lambda because it contains a statement block {...} to the right side of the expression. Expression lambda takes the form: number => (number % 2 == 0) Statement lambda takes the form: number => { return number > 5 }

Categories : C#

Error when using a Linq Expression variable instead of lambda expression directly
Compile your expression into executable code (delegate): var types = assembly.GetTypes().AsEnumerable().Where(_standardFilter.Compile()); As @Kirk stated, it's better not to use expression tree, if you are not going to analyze it. Simply use filter of type Func<Type, bool>.

Categories : C#

How to generate a lambda at runtime passing a property name as string?
Your first attempt is closer to the solution. You just need to call the generic version of Lambda: var lambda = Expression.Lambda<Func<PolicyTran, object>>(body, x).Compile(); in order to get a Func<PolicyTran, object> delegate. Otherwise the labda will return a simple System.Delegate from which the LINQ .Select will be unable to infer the types.

Categories : C#

Lambda Expression with Inner Lambda Expression
typeof only applies to type names. If you need the run-time type of c, you must use Object.GetType and say c.GetType(). So, the compiler sees typeof(c) and knows that typeof only accepts type names and is therefore trying valiantly to find a type named c somewhere, anywhere but, alas, it can't. So, it's telling you "I can't find the type c."

Categories : C#

Translating to lambda expression
This is the exact translation. I have no idea why you need the OrderBy tho, considering you are not using the elements in the Select var methods = typeof(double).GetMethods() .OrderBy(x=>x.Name) .GroupBy(x=>x.Name) .Select(x=> new { MethodName = x.Key, NumberOfOverloads = x.Count()}); The same result is obtained by var methods = typeof(double).GetMethods() .GroupBy(x=>x.Name) .Select(x=> new { MethodName = x.Key, NumberOfOverloads = x.Count()}); and you save some computational time since you don't have to order the collection.

Categories : C#

Passing expression into lambda
The approach using Reflection: var result = myList.Where(obj => obj.GetType() .GetProperty("Text1") .GetValue(obj) .Equals("SomeString")); With this way you can change from "Text1" to "Text2" property. Another approach you can use dynamic linq: var result = myList.AsQueryable().Where("Text1=@0", "SomeString"); Dynamic LINQ is also available via nuget.

Categories : C#

How to write a VB.Net Lambda expression
The lambda syntax isn't that much different than creating a regular delegate. If creating a lambda which has a return value, use Function. Otherwise if you're creating one that doesn't, use Sub. Dim _new = orders.Select(Function(x) x.Items > 0) Dim action As Action(Of Item) = Sub(x) Console.WriteLine(x.Items)

Categories : Linq

c# my sql statement to lambda expression
try below var result = question.GroupBy(x=>new{x.QuestionNo , x.ActivityID}) .Select(g=> new {QuestionNo= g.Key.QuestionNo, ActivityID= g.Key.ActivityID, joined = string.Join(" ", g.Select(i=>i.Question+ "[" + i.Answer +"]"))}) .Take(30); If you want to return this from method you can create new class like below public class Question { public int QuestionNo {get;set;} //change the type accordingly public string ActivityID {get;set;} //change the type accordingly public string joined {get;set;} //change the type accordingly } and change the method to : public IList<Question> GetList() { IList<Question> lstRecords = context.questions.GroupBy(x => new { x.QuestionNo, x.ActivityID }) .Select(g =>

Categories : C#

How to resolve Lambda Expression
OK, I think this works: NServiceBus.SetLoggingLibrary.Log4Net((Action)(() => MyConfiguration.ConfigureLog4Net("myLog"))); or NServiceBus.SetLoggingLibrary.Log4Net(new Action(() => MyConfiguration.ConfigureLog4Net("myLog")));

Categories : C#

Convert sql to Lambda expression
Here is how you can do it var galleryIds = (bidModelses.Where(b => b.UserId == [YOURPARAMETER]) .Select(b => b.GalleryId)); var query = (bidModelses.Where(bm => galleryIds.Contains(bm.GalleryId)) .GroupBy(bm => bm.GalleryId) .Select(gbm => new {gbm.Key, MaxBid = gbm.Max(p => p.BidId)}));

Categories : SQL

How to read this lambda expression
this function n => n % 2 == 1 takes one argument (n) and return boolean value: true, if n is odd: n % 2 == 1 (n is odd if and only if it has remainder 1 when divided by 2) false otherwise (if n is even) When re-written as ordinary function it would be equivalent to Boolean IsOdd(int n) { -- <- I've named it "IsOdd" since lambda functions have no explict names while ordinary functions have return n % 2 == 1; } Your code below List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList(); i's a LINQ expression which selects odd values from the list

Categories : C#

Lambda runtime exception 'variable ' ' of type ' ' referenced from scope '', but is not defined
You're missing an open curly bracket after d is defined. I have added a return as well. Try the following: DataMore1 dm1 = null; DataMore2 dm2 = null; var list = session.QueryOver<Data>() .JoinAlias(data => data.DataMore1, () => dm1, NHibernate.SqlCommand.JoinType.LeftOuterJoin, Expression.Eq("Segment", 0)) .JoinAlias(data => data.DataMore2, () => dm2, NHibernate.SqlCommand.JoinType.LeftOuterJoin, Expression.Eq("Segment", 0)) .ToList() .Select(d => { return new Data () { PlantID = d.PlantID, AreaID = d.AreaID, CellID = d.CellID, DeviceID = d.DeviceID, StartDateTime = d.StartDateTime, DataPoint01 = d.DataPoint01,

Categories : C#

How to specify an Include inside a lambda expression
Have you tried this? return project.Servers .Include(a => a.OperatingSystem) .Include(a2 => a2.DataCenter) .Include(a3=>a3.Rack) .Include(a4=>a4.ServerModel) .Include(a5=>a5.Technology) .Include(a6=>a6.VirtualMachines) .Include(a7=>a7.TechnologyStatu) .Include(a8=>a8.TechnologyBackUpStatu) .Include(a9=>a9.TechnologyRole) .Where(srv => srv.Rack.RackID == id);

Categories : C#

How to use local variables in a lambda expression
Use a statement lambda instead of an expression lambda HashSet<string> inconsistantIDs = new HashSet<string>( pr.Select(p => p.id).Where(p => { var count = tem.FindAll(t => t.id == p).Count; return count == 0 || count % 2 != 0; } ));

Categories : C#

Double filter with lambda expression
You can add multiple conditions using "&&" (which is equivalent to "AND" in SQL) or "||" (which is equivalent to "OR" in SQL). You can also use the LINQ "Any()" method to return true if one or more elements in the collection match a condition. So your if statement would read: if(products.Any(x=>x.code.Equals(Code.Text) && !x.id.Equals(Id.Text))){ CodeExists = true; } EDIT: Fixed minor typo with "!" placement.

Categories : C#

Function taking lambda expression
There is two things in your code that will not work. First, when passing a lambda function as argument, I suggest using Template. The standard library on Microsoft seems to use this method for std::for_each for example. And : When function template has a return type, which cannot be deduced from arguments, or when function template doesn't have any argument, the type cannot be deduced by the compiler. This function will require template type argument specification. Take a look at this example : template<class Tout, class Tin, class Fun> // ^^^^^^^^^^^ // Note that I changed the order of the types std::vector<Tout> map( const std::vector<Tin>& in, Fun mapper ) { // ^^^^^^^^^^ std::vector

Categories : C++

Lambda Generic Expression w/ Out Parameter
I don't think it's possible. On Compiler Error CS1951 they write: An expression tree just represents expressions as data structures. There is no way to represent specific memory locations as is required when you pass a parameter by reference.

Categories : C#

How to use ToShortDateString in linq lambda expression?
Linq to Entities cannot convert ToSortDateString method into SQL code. You can't call it on server side. Either move filtering to client side (that will transfer all data from server to client), or consider to use server-side functions to take date part of date (you should pass DateTime object instead of shortDateString): EntityFunctions.TruncateTime(p.date) == dateWithoutTime

Categories : C#

Expression lambda Dynamic Parameter
As I said in my comment, I think this is a bad idea. However, there's an (untested) trivially simple way to implement the behavior I think you're looking for. public IQueryable GetCompaniesDynamic(string table, string property, string search) { using (var context = new DBContext()) { return context.Database.SqlQuery("SELECT * FROM dbo." + table + " WHERE " + property + " = '" + search + "'"); } } You use it like: var companies = GetCompaniesDynamic("News", "Name", "myNews"); Note that this leaves you vulnerable to SQL injection if you don't sanitize your input, spelling mistakes and typos which you won't catch until your application blows up at runtime, and simply forgetting what fields are called. I don't know why you're

Categories : C#

How to implement AND logic in lambda expression?
Use an anonymous type for the join from x in UserInteractions join x2 in UserInteractions on new {x.sourceuser_id, x.targetUser_id} equals new {x2.sourceuser_id, x2.targetuser_id} select new .... blah blah or... UserInteractions .Join ( UserInteractions , x => new { x.sourceuser_id, x.targetuser_id }, x2 => new { x2.sourceuser_id, x2.targetuser_id }, (x, x2) => //Whatever it is you want to project out.... )

Categories : C#

counter in lambda expression streamwriter
You could declare the counter outside of the foreach lambda, just as you would declare it outside of the scope of a foreach loop. var x = 1; myGrid.ForEach(model => myStreamWriter.WriteLine(x++.ToString()));

Categories : Linq

What's the point of lambda expression in OrderBy?
When you order a collection it doesn't change it's type, hence IEnumerable<Something> somethings = ...; var strings = somethings.OrderBy(a => a.StringProperty); results in an IEnumerable<Something>, you have to select the property to change the type: IEnumerable<String> strings = somethings .OrderBy(s => s.StringProperty) .Select(s => s.StringProperty); So why am I enforced to use the lambda expression in the OrderBy command?! Because Enumerable.OrderBy is a method that needs an argument.

Categories : C#

Model error, lambda expression
It looks like you've created an anonymous type needlessly with this line: .Select(s => new { s.Modulos.Modulos}) Try instead simply (should return an IEnumerable<Modulos>): .Select(s => s.Modulos.Modulos)

Categories : C#

Is C#'s lambda expression grammar LALR(1)?
First off, parser theory was always one of my weak points. I mostly work on semantic analyzers. Second, all the C# parsers I've ever worked on have been hand-generated recursive descent parsers. One of my former colleagues who does have a strong background in parser theory did build his own parser generator and fed the C# grammar into it successfully, but I do not know what sort of egregious hacks doing so entailed. So what I'm saying here is to take this answer with the appropriate amount of skepticism. As you note, lambdas are slightly vexing because you've got to be careful about that parenthesized expression -- it might be a parenthesized expression, a cast operator or a lambda parameter list, and the lambda parameter list could be in several different forms. But all things con

Categories : C#

Get duplicated row in two datatable using lambda expression
I would try following: ' prepare HashSet from keys from table2 ' Dim table2Keys = new HashSet(Of Tuple(Of String, String)) set.UnionWith(table2.AsEnumerable().Select(Function(x) Tuple.Create(x("item1"), x("item2")) ' search table1 for duplicates ' Dim result = table1.Where(Function(x) table2Keys.Contains(Tuple.Create(x("item1", y("item2"))) It should have better performance then using Any, because HashSet lookup can be done in O(1).

Categories : Vb.Net

Initializing a variable by a lambda expression?
You need to call the lambda: int i( []() { return 1; }() ); // ^^ The lambda itself is an expression that yiels a a prvalue temporary called a closure object. These are not convertible to int.

Categories : C++

Yielding from inside a lambda expression in F#
You have to yield the uncloned array. There is the obvious strange behaviour in that if you call toList on the sequence then you get an array of the last value of the array. So the first thing you have to do is Seq.map it with the clone function. Also I don't think there is a need to make your function recursive if you are allready working with mutables. let permutations (alphabet:'a array) = let swap i j = let aux = alphabet.[i] alphabet.[i] <- alphabet.[j] alphabet.[j] <- aux let rec permutations' n = seq { if n = alphabet.Length then yield alphabet else for i in n..(alphabet.Length-1) do swap n i yield! permutations' (n+1)

Categories : Dotnet

python max function using 'key' and lambda expression
Strongly simplified version of max: def max(items, key=lambda x: x): current = item[0] for item in items: if key(item) > key(current): current = item return current Regarding lambda: >>> ident = lambda x: x >>> ident(3) 3 >>> ident(5) 5 >>> times_two = lambda x: 2*x >>> times_two(2) 4

Categories : Python

MVC4 lambda expression for SimpleMembership
You can use LINQ: var users = (from users in UserProfile from userRoles in users.UsersInRole from roles in userRoles.Role select new { UserName = users.UserName , UserId = users.UserId , RoleName = roles.RoleName , RoleId = roles.RoleId }).ToList();

Categories : C#

Lambda Expression if-else statement in where clauses
I would prefer extension method syntax in this situation and do it like so: IQueryable<User> query = entities.Users; switch (userField) { case "ID": int searchID; if (int.TryParse(searchText, out searchID)) query = query.Where(u => u.ID == searchID); else query = query.Where(u => false); break; case "Name": query = query.Where(u => u.Name == searchText); break; case "Email": query = query.Where(u => u.Email == searchText); break; } var users = new { total = 10, page = page, record = (entities.Users.Count()), rows = (from user in query select new // etc. ) };

Categories : C#

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

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#

Unable to figure out this (Statement) Lambda Expression
Both are lambdas that result in anonymous objects. Also, both are written in a very terse form, the complete form would be: (s) => { return new { s.Index }; } The second is equivalent. Both lambdas are Func<> delegates, with varying signatures. A lambda can result in a string, but that depends on what you are using it for (type inference is a huge thing here and one of the reasons lambdas are very terse). The return type of a lambda depends on the context you are using it in - it can be a delegate, but in your case, it isn't. A lambda is a delegate though - if it has a return type, it's a Func<T1, T2, ... Tn, TReturn>, if it doesn't, it's Action<T1,T2,..., Tn>.

Categories : C#

Regex substitution: what is the difference between $& and Value (in lambda expression)?
Lambdas are anonymous methods which work just the same as regular ones. The one declared in your example is equivalent to: string Convert(RegexMatch match) { return "test" + match.Value; }. Using this syntax can give you access to a much richer range of possibilities then using the Regex expression used in your first example.

Categories : C#

MVC Cannot convert lambda expression to type because it is not a delegate
Found what happens. The asp.net tags are not allowed in the SetContent() that way. The correct way to do it is: CBsettings.SetContent(() => { ViewContext.Writer.Write("<h1>Hello World</h1>"); ... }); So sad the intellisense doesn't give a clue about what is wrong.

Categories : C#

Conditional SELECT in Lambda expression LINQ
The problem is that because you are returning multiple different types of objects the compilers isn't sure what objet type you are expecting in your returned enumerable. Usually when you use something like Select or SelectMany the compiler can work it out so you don't need to worry about it. In this case you need to worry about telling it what they should be. Your code will be changed to look like: return this.WrappedEntity.human_screen.SelectMany(e => e).Select<TSource, TResult>(e => { //Same code as before in here }); TSource should be the type of e in your select method. TResult should be the base type of SqlFemaleScreening, SqlMaleScreening, SqlChildScreening.

Categories : C#

Lambda expression as parameter to be used as AsTask() callback
The AsTask extension method you use does not contain a signature that accepts delegate/Func, so you can't do .AsTask(...=>...) But you can use lambda in this line: var progressCallback = new Progress<DownloadOperation>(...=>...); Since the constructor of Progress<T> accepts an Action<T>

Categories : C#

Lambda expression to Iterate through a collection and edit C#
Don't use Linq to modify collections, use loops instead: So this is the best approach (have a look at the UriBuilder Class): foreach (var l in urllist) { l.Url = string.Format("{0}?id={1}&active={2}", l.Url, client.id, client.Active); } You have to create a new collection otherwise what is less efficient than modifying the original collection: urllist = urllist .Select(l => {l.Url = string.Format("{0}?id={1}&active={2}", l.Url, client.id, client.Active; return l;}) .ToList(); If urllist is a List<T> you could also use the pre-linq .NET 2 method ForEach: urllist.ForEach(l => l.Url = string.Format("{0}?id={1}&active={2}", l.Url, client.id, client.Active));

Categories : C#

Why C# lambda expression can't use instance properties and fields?
You cannot access an object instance before its constructor runs (such as in a field initializer or base constructor call). This is true both inside a lambda and outside a lambda. C# < 4 had a bug that allowed this in certain cases.

Categories : C#



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