30,332 questions
1871
votes
4
answers
124k
views
Is there a reason for C#'s reuse of the variable in a foreach?
When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example:
foreach (var s in strings)
{
query = query.Where(i => i.Prop ...
1776
votes
11
answers
708k
views
What is a lambda expression, and when should I use one?
What is a C++ lambda expression? Why does C++ have them, what problems do they solve that were not solvable prior to their addition? And how can I benifit from using them?
Please provide an example or ...
1165
votes
19
answers
955k
views
List comprehension vs. lambda + filter [closed]
I have a list that I want to filter by an attribute of the items.
Which of the following is preferred (readability, performance, other reasons)?
xs = [x for x in xs if x.attribute == value]
xs = ...
1159
votes
12
answers
320k
views
Why would you use Expression<Func<T>> rather than Func<T>?
I understand lambdas and the Func and Action delegates. But expressions
stump me.
In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>?
1075
votes
23
answers
815k
views
Java 8 List<V> into Map<K, V>
I want to translate a List of objects into a Map using Java 8's streams and lambdas.
This is how I would write it in Java 7 and below:
private Map<String, Choice> nameMap(List<Choice> ...
1002
votes
18
answers
195k
views
What is the difference between a 'closure' and a 'lambda'?
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.
And now that we're here, how do they differ from a regular function?
986
votes
26
answers
597k
views
How are lambdas useful? [closed]
I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language items that in real life should be forgotten?
I'm sure there are some edge cases where it might be ...
852
votes
24
answers
413k
views
What is a lambda (function)?
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
839
votes
20
answers
483k
views
Distinct() with lambda?
Right, so I have an enumerable and wish to get distinct values from it.
Using System.Linq, there's, of course, an extension method called Distinct. In the simple case, it can be used with no ...
676
votes
19
answers
416k
views
Getting all types that implement an interface
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
foreach (Type t in this....
651
votes
28
answers
553k
views
Java 8 Lambda function that throws exception?
I know how to create a reference to a method that has a String parameter and returns an int, it's:
Function<String, Integer>
However, this doesn't work if the function throws an exception, say ...
608
votes
23
answers
298k
views
Retrieving Property name from lambda expression
Is there a better way to get the Property name when passed in via a lambda expression?
Here is what i currently have.
eg.
GetSortingInfo<User>(u => u.UserId);
It worked by casting it as a ...
569
votes
10
answers
1.3m
views
Join/Where with LINQ and Lambda
I'm having trouble with a query written in LINQ and Lambda. So far, I'm getting a lot of errors here's my code:
int id = 1;
var query = database.Posts.Join(
database.Post_Metas,
post => ...
529
votes
16
answers
904k
views
Is there a way to perform "if" in python's lambda? [duplicate]
In Python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to ...
519
votes
26
answers
325k
views
No Multiline Lambda in Python: Why not?
I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and ...
515
votes
9
answers
157k
views
When should I use arrow functions in ECMAScript 6?
With () => {} and function () {} we are getting two very similar ways to write functions in ES6. In other languages lambda functions often distinguish themselves by being anonymous, but in ...
512
votes
15
answers
485k
views
Retrieving a List from a java.util.stream.Stream in Java 8
I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach ...
505
votes
16
answers
444k
views
How do I define a method which takes a lambda as a parameter in Java 8?
In Java 8, methods can be created as Lambda expressions and can be passed by reference (with a little work under the hood). There are plenty of examples online with lambdas being created and used with ...
489
votes
10
answers
815k
views
List<T> OrderBy Alphabetical Order
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I ...
435
votes
15
answers
535k
views
Break or return from Java 8 stream forEach?
When using external iteration over an Iterable we use break or return from enhanced for-each loop as:
for (SomeObject obj : someObjects) {
if (some_condition_met) {
break; // or return obj
...
434
votes
21
answers
30k
views
Reflecting parameter name: abuse of C# lambda expressions or syntax brilliance? [closed]
I am looking at the MvcContrib Grid component and I'm fascinated, yet at the same time repulsed, by a syntactic trick used in the Grid syntax:
.Attributes(style => "width:100%")
The syntax above ...
398
votes
15
answers
215k
views
Difference between final and effectively final
I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous ...
387
votes
4
answers
271k
views
Java 8 lambdas, Function.identity() or t->t
I have a question regarding the usage of the Function.identity() method.
Imagine the following code:
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity()) // <- ...
386
votes
8
answers
98k
views
What do lambda function closures capture? [duplicate]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code:
adders = [None, None, None, None]
for i in [0, 1, 2, 3]:
...
378
votes
18
answers
170k
views
How can I throw checked exceptions from inside Java 8 lambdas/streams?
How can I throw checked exceptions from inside Java 8 lambda, used in a stream for example?
In other words, I want to make code like this compile:
public List<Class> getClasses() throws ...
373
votes
10
answers
328k
views
Java 8 lambda Void argument
Let's say I have the following functional interface in Java 8:
interface Action<T, U> {
U execute(T t);
}
And for some cases I need an action without arguments or return type. So I write
...
370
votes
12
answers
312k
views
Passing capturing lambda as function pointer
Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.
Consider the following example
using DecisionFn = ...
358
votes
8
answers
154k
views
E731 do not assign a lambda expression, use a def
I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?
346
votes
26
answers
400k
views
Filter Java Stream to 1 and only 1 element
I am trying to use Java 8 Streams to find elements in a LinkedList. I want to guarantee, however, that there is one and only one match to the filter criteria.
Take this code:
public static void main(...
346
votes
14
answers
85k
views
When to use lambda, when to use Proc.new?
In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other.
What are those differences?
Can you give guidelines on how to decide which one to choose?
In ...
346
votes
1
answer
51k
views
A positive lambda: '+[]{}' - What sorcery is this? [duplicate]
In Stack Overflow question Redefining lambdas not allowed in C++11, why?, a small program was given that does not compile:
int main() {
auto test = []{};
test = []{};
}
The question was ...
343
votes
13
answers
133k
views
Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?
Short example:
#include <iostream>
int main()
{
int n;
[&](){n = 10;}(); // OK
[=]() mutable {n = 20;}(); // OK
// [=](){n = 10;}(); // Error: a by-...
341
votes
4
answers
311k
views
Java 8 Streams: multiple filters vs. complex condition
Sometimes you want to filter a Stream with more than one condition:
myList.stream().filter(x -> x.size() > 10).filter(x -> x.isCool()) ...
or you could do the same with a complex condition ...
335
votes
10
answers
167k
views
Combining two expressions (Expression<Func<T, bool>>)
I have two expressions of type Expression<Func<T, bool>> and I want to take the OR, AND, or NOT of these and get a new expression of the same type.
Expression<Func<T, bool>> ...
327
votes
12
answers
277k
views
`break` and `continue` in `forEach` in Kotlin
Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local):
repeat(5) {
break
}
(1..5)....
321
votes
16
answers
255k
views
C# Lambda expressions: Why should I use them?
I have quickly read over the Microsoft Lambda Expression documentation.
This kind of example has helped me to understand better, though:
delegate int del(int i);
del myDelegate = x => x * x;
int ...
319
votes
14
answers
225k
views
Can lambda functions be templated?
In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?
I understand that I can define a classic templated class/functor instead, but the question is ...
319
votes
13
answers
289k
views
Using Java 8's Optional with Stream::flatMap
The new Java 8 stream framework and friends make for some very concise Java code, but I have come across a seemingly-simple situation that is tricky to do concisely.
Consider a List<Thing> ...
311
votes
3
answers
270k
views
Where do I mark a lambda expression async?
I've got this code:
private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
CheckBox ckbx = null;
if (sender is CheckBox)
{
ckbx = ...
307
votes
12
answers
564k
views
Sorting a list using Lambda/Linq to objects
I have the name of the "sort by property" in a string. I will need to use Lambda/Linq to sort the list of objects.
Ex:
public class Employee
{
public string FirstName {set; get;}
public string ...
306
votes
7
answers
210k
views
Is it possible to type hint a lambda function?
Currently, in Python, a function's parameters and return types can be type hinted as follows:
def func(var1: str, var2: str) -> int:
return var1.index(var2)
Which indicates that the function ...
301
votes
4
answers
156k
views
How to merge a list of lists with same type of items to a single list of items?
The question is confusing, but it is much more clear as described by the following code:
List<List<T>> listOfList;
// add three lists of List<T> to listOfList, for example
/*...
285
votes
14
answers
379k
views
convert a list of objects from one type to another using lambda expression
I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result.
var origList = List<...
285
votes
1
answer
16k
views
How is "int main(){(([](){})());}" valid C++?
I recently came across the following esoteric piece of code.
int main(){(([](){})());}
Reformat it as follows to make it more readable:
int main(){
(([](){})()); // Um... what?!?!
}
But I can'...
284
votes
13
answers
548k
views
How to use a Java 8 lambda to sort a Stream in reverse order?
I'm using a Java lambda to sort a list.
How can I sort it in a reverse way?
I saw How to sort ArrayList<Long> in decreasing order?, but I want to use a Java 8 lambda.
Here is my code (I used * -...
277
votes
1
answer
225k
views
Multiple Order By with LINQ [duplicate]
I start with a basic class that I want to manipulate in a List using LINQ, something like the following:
public class FooBar
{
public virtual int Id { get; set; }
public virtual string ...
275
votes
8
answers
460k
views
python max function using 'key' and lambda expression
I come from OOP background and trying to learn python.
I am using the max function which uses a lambda expression to return the instance of type Player having maximum totalScore among the list players....
270
votes
1
answer
117k
views
How to remove a lambda event handler [duplicate]
I recently discovered that I can use lambdas to create simple event handlers. I could for example subscribe to a click event like this:
button.Click += (s, e) => MessageBox.Show("Woho");
...
266
votes
7
answers
497k
views
Filter values only if not null using lambda in Java8
I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values?
Current ...
265
votes
9
answers
466k
views
Variable used in lambda expression should be final or effectively final
Variable used in lambda expression should be final or effectively final
When I try to use calTz it is showing this error.
private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone ...