Introduction to Lambda Expressions
In one of our earlier blogs, we had explored SOLID principles. According to that, creating dedicated classes and methods that perform a single activity is one of the best practices to follow. Imagine creating a method but it is being utilized only once in the code. As per the project visibility, it is not going to be used up anytime in the future also. In such cases, the efforts in defining a method, type of input, and output is considerably high due to the number of times it is being utilized throughout the code.
In such cases, a one-time usable method with lower concentration on implementation, parameter specification, declaration, access specifier, return value, and name allows us to write the method in the same place as it is required. This will be quite handy to accomplish the task.
Luckily, C# from its version 3.0 (.Net framework 3.5), provides lambda expressions to create anonymous methods that can be used to write expressions. This is nothing but the sequence of operations which are used only in one instance and which also allows writing single or multiple lines of the anonymous method based on the need. Let's see in detail what are lambda expressions in this blog.
Table of contents
- What are Lambda Expressions?
- How to use Lambda Expression in C#?
- Conclusion
What are Lambda Expressions?
Lambda expressions provide the ability to create anonymous functions. Every lambda expression consists of the lambda operator ‘=>’ which splits the input parameters for the anonymous method and the operations that are being carried out based on that.
(input-parameter) => expression
(input-parameter) => { sequence of statements to execute }
Lambda expressions can be converted to delegate types. Lambda expressions that have an input parameter and no return type can be converted as Action Delegate type.
Example -
Action<string> welcomeUser = inputName =>
{
Console.WriteLine(string.Format(“Welcome {0}.”, inputName));
}
welcomeUser(“PARTECH”);
Similarly, lambda expressions that have a parameter and return type can be converted as Func Delegate type.
Example -
Func<int, int> radiusOfCircle = inputRadius => (3.14 * inputRadius * inputRadius);
Console.WriteLine(radiusOfCircle(5));
Here, the Func<int, int> indicates the data type of input and result respectively.
How to use Lambda Expression in C#?
In this section, let us see some practical examples where lambda expressions can be used in C#.
Scenario 1
Imagine a scenario where a list of strings holds certain data which needs to be displayed in comma-separated format. With Lambda expressions it is simple to achieve it.
var data = new List<string> { "One", "Two", "Three", "Four", "Five" };
var result = String.Join(", ", data.Select(x => x));
The result will be - “One, Two, Three, Four, Five”
Scenario 2
Imagine a scenario, where a list of strings is present, and we need to prefix it with some data to process it together. Let's see how to achieve this using lambda expression.
var data = new List<PartechNonGeneric> { new PartechNonGeneric { Property = false, Data ="One" } };
data.ForEach(x => x.Data = "PARTECH_" + x.Data);
In this scenario, the prefix data ‘PARTECH_’ gets appended to all the objects that are present in the collection.
Scenario 3
To check whether a particular data is present in the collection, lambda expressions can be used. Consider a scenario where the user wants to check if the first name exists in a collection. In such a scenario lambda expressions can be used.
var data = new List<PartechPersonalData> { new PartechPersonalData{ FirstName= “Test”, LastName="User" } };
var exists = data.Exists(x => x.FirstName = "PARTECH");
The above code returns true if the data of the selected filter is present else it returns false.
Scenario 4
Consider a list of custom classes and there is a necessity to filter out the object that contains the first name as xx. Post this, do some operations with the specific object rather than the entire list itself (such as the foreach operation which we saw previously).
var data = new List<PartechPersonalData> { new PartechPersonalData{ FirstName= “Test”, LastName="User" },
new PartechPersonalData{ FirstName= “Test2”, LastName="User" } };
var partechData = data.Find(x => x.FirstName = "Test");
The above code returns the first object that is present in the collection that matches the provided condition as a lambda expression.
Scenario 5
To return multiple objects that match similar conditions, the below code can be used. Imagine a scenario where there is a need to filter students who are 18 years and above. There is a possibility that multiple student records will be present for that condition. With lambda expressions, it is possible to capture all the objects that pass that condition.
var data = new List<PartechPersonalData> { new PartechPersonalData{ FirstName= “Test”, LastName="User", DateOfBirth = “2002-02-21” },
new PartechPersonalData{ FirstName= “Test2”, LastName="User", DateOfBirth = “2002-02-28” } };
var partechData = data.FindAll(x => (x.DateOfBirth.Year - DateTime.Now.Year) >= 18);
The above code checks through all the records that are present in the custom list and checks for the condition that is being defined and returns all the objects that match the condition provided.
Scenario 6
To return a single property for all the objects that are present in a collection, lambda expressions can be used. Imagine a custom class that holds the first name, last name, and dob. Consider a scenario where there is a necessity to get only the first names that are present in the collection. With lambda expression, it is possible to retrieve only the selected property from the custom class collection.
var data = new List<PartechPersonalData> { new PartechPersonalData{ FirstName= “Test”, LastName="User", DateOfBirth = “2002-02-21” },
new PartechPersonalData{ FirstName= “Test2”, LastName="User", DateOfBirth = “2002-02-28” } };
var firstNameData = data.Select(x => x.FirstName);
In the above code, the Select statement with the property provides the first name alone from the custom collection.
Similar to the above scenarios, many other operations can be performed with the lambda expressions such as modifying and formatting strings, date format, performing calculations etc.
Conclusion
Lambda expressions are a powerful tool to have. It makes it possible to achieve data manipulation, custom selection, and many other popular operations. The best part is it is done just using simple anonymous methods, lambda operators and input data.