•

Check out our Community Blogs Register and join over 40,000 other developers!

### Popular Tags      # c# introduction to lambda functions and LINQ

3 replies to this topic

### #1 chili5

chili5

CC Mentor

• Expert Member
•        • 3038 posts
• Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
• Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 13 August 2011 - 03:15 PM

C# Lambda Functions and Introduction to LINQ

1. C# Lambda Functions and Introduction to LINQ
2. C# LINQ Sorting

Before, I start writing about LINQ queries it is important to discuss lambda functions. Lambda functions are a crucial aspect of functional programming languages (such as Scheme and Haskell) but are now included in several imperative languages such as C# and JavaScript.

What are Lambda Functions?

A lambda function is a function that doesn’t have an explicit name. These are often useful for functions that are just used once but are so simple that they do not need to have a name.
For example consider this function that squares 2 numbers:
```int square(int x) {
return x * x;
}
```
This function is relatively simple and we can figure out what it does fairly easily without having to name it. So instead we could write a lambda function to square 2 numbers.
In c# this is written as x => x * x
The => is referred to as the lambda operator and is pronounced “goes to”. In a mathematical sense we can think of this function being defined as f(x) = x * x. The function takes a parameter x and produces the value x * x.

Introduction to LINQ

As a practical example of a lambda function let us introduce LINQ. LINQ is a way of performing operations on various collections of data using a standard notation.
Consider a simple problem with arrays. We have an array of integers and we want to find all the even integers and put them into an array.

This actually isn’t quite as easy a problem as it sounds if we don’t want to waste any memory. We have two options we can loop through the array once to count the number of even items. Then we can iterate the array again to build the new array. A second option is we can create a new array that is the same size of the original array and then try to reallocate the memory so we don’t waste any memory. This second option requires us to use C# in unsafe mode so we can use pointers and do our own memory management much like we would in C.
Either way, we have a lot of our processing to do to accomplish this task. With LINQ as we will see, you can solve these kinds of problems without having to think about these details.
One way to write this solution is as follows:
```var results = (from itm in v
where itm % 2 == 0
select itm).ToArray();
```

Note, var is an implicit variable type where C# determines the type of the variable based on how it is used. In this case the type of results is int[].
Think of “from itm in v” as meaning for each element itm in v. Then we check the itm % 2 == 0 clause on each item and if that is true, we select itm as part of the collection. The query when executed builds a collection of items from v that are even. Then we convert it to an array.
More details about LINQ to follow another day. But how does lambda functions fit into this? Wouldn’t it be nice if we could use LINQ without having to think about how to write the query?
The previous example can be written as:

```var results2 = v.Where(k => k % 2 == 0).ToArray();
```

Here what is happening is we are saying take all elements in v that the lambda function in the Where clause is true and add those items to an array.
The lambda function k => k % 2 == 0 is a predicate that takes a parameter k and returns true if k % 2 == 0. If the predicate is true then the element will be added to the resulting array.
The predicate in the Where clause will be executed once on each element in the collection v.

Change in Data Structures
If we were going to use a loop to accomplish these tasks if we changed data structures we would have to rewrite the loop. The power of LINQ comes when we change the data structure we don`t have to rewrite the queries.

```
var x = new List<int> {3, 2, 5, 4, 6, 7, 8, 0, 2};

var results3 = x.Where(k => k%2 == 0).ToArray();

foreach (var itm in results3)
Console.WriteLine(itm);
```

Notice, that the Where clause is exactly the same and the only change is the type of the data structure.

Next time, we will look at more advanced selects and to do this we will have to introduce anonymous types.
Challenges:

• Create a LINQ query and lambda function that selects all odd numbers from an array.
• Create a linked list of strings and select all that have at least 3 characters.
• Create an array of strings and find all items that are all lowercase. Return the items as a list, not an array.

1. C# Lambda Functions and Introduction to LINQ
2. C# LINQ Sorting

Edited by chili5, 17 August 2011 - 12:41 PM.

• 0

### #2 John

John
• Location:New York, NY

Posted 16 August 2011 - 02:05 PM

Oh, I probably should have read this one first If you are going to do tutorials that build off each other, could you add a link to the next and previous tutorials at the bottom and top (like what Rhetorical is doing here http://forum.codecal...m-part-2-a.html)?
• 0

### #3 chili5

chili5

CC Mentor

• Expert Member
•        • 3038 posts
• Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
• Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 17 August 2011 - 12:43 PM

Yes - I updated the LINQ ones.
• 0

### #4 John

John
• Location:New York, NY

Posted 17 August 2011 - 05:26 PM

Awesome. Thanks!
• 0

### Also tagged with one or more of these keywords: linked list, realloc, variable type

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download 