C# Lambda in List

In C#, One of the most powerful features is lambda expressions, using them developers can write more concise and expressive code. Today we learn and explore how to use lambda expressions on lists in C# to perform various operations such as filtering, sorting, finding elements, and more.

KEY TAKEAWAYS:

  1. C# Lambda in List can be used to filter, sort, find, iterate, and perform other operations.
  2. As Lambda expressions has very short and expressive syntax, they let us write code which is more readable and maintainable.
  3. C# Lambda with List can be used with a variety of list operations, including Where, Select, Find, ForEach, and Sort.
  4. C# Lambda Where method can be used to filter a list based on a condition. The Select method can be used to project each element of a list into a new form. The Find method we can use to search for an element in a list.
  5. You will see many code samples available to illustrate the use of C# lambda in Lists. These samples can be used to learn how to use lambda expressions with different list operations.

Table of Contents:

C# Lambda in List

  1. How to filter list in C# with Lambda expression
  2. Projecting with Select Method
  3. Finding Elements with Find Method
  4. Iterating with ForEach
  5. Sorting with Sort Method
  6. 26 Code Samples for C# Lists with Lambda Expressions
  7. Conclusion

How to filter list in C# with Lambda expression

Lambda expressions can be used with list operations to make them more concise and expressive. Here we have some common list operations and how to use lambda expressions with them:

Filtering with Where:

The "Where" method is used to filter a list based on a given condition. It takes a lambda expression as a parameter and returns a new list containing only the elements that meet the condition.

Example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();

Projecting with Select

The "Select" method in C# can be used to project each element of a list into a new form. It takes a lambda expression as a parameter and returns a new list with the projected elements.

Example:

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
List<int> nameLengths = names.Select(name => name.Length).ToList();

Finding Elements with Find

Using "Find" method we can search for an element in a list. It takes a lambda expression as a parameter and returns the first element that satisfies condition.

Example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int firstEvenNumber = numbers.Find(x => x % 2 == 0);

Iterating with ForEach

We can use "ForEach" method to perform an action on each element of a list. It takes a lambda expression as a parameter and executes the action for each element.

Example:


List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.ForEach(name => Console.WriteLine(name));

Sorting with Sort

The "Sort" method in C# can be used to sort a list based on a specified comparer. It takes a lambda expression as a parameter and sorts the list according to the provided comparison logic.

Example:

List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };
numbers.Sort((x, y) => x.CompareTo(y));
						

26 Code Samples for C# Lists with Lambda Expressions

Here are 26 code samples demonstrating various ways to use C# lists with lambda expressions:

  1. Filter a list of integers for even numbers:
    List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
    
  2. Filter a list of strings for those containing a specific substring:
    List<string> filteredStrings = strings.Where(s => s.Contains("keyword")).ToList();
    
  3. Count elements in a list that match a given condition:
    int count = numbers.Count(x => x > 10);
    
  4. Check if any element in a list matches a given condition:
    bool hasNegative = numbers.Any(x => x < 0);
    
  5. Check if all elements in a list match a given condition:
    bool allPositive = numbers.All(x => x >= 0);
    
  6. Find the maximum element in a list:
    int max = numbers.Max();
    
  7. Find the minimum element in a list:
    int min = numbers.Min();
    
  8. Calculate the sum of all elements in a list:
    int sum = numbers.Sum();
    
  9. Calculate the average of all elements in a list:
    double average = numbers.Average();
    
  10. Concatenate two lists:
    List<int> concatenatedList = list1.Concat(list2).ToList();
    
  11. Create a dictionary from a list:
    Dictionary<int, string> dict = list.ToDictionary(x => x.Key, x => x.Value);
    
  12. Remove duplicates from a list:
    List<int> distinctNumbers = numbers.Distinct().ToList();
    
  13. Reverse the order of elements in a list:
    List<int> reversedList = numbers.Reverse().ToList();
    
  14. Group elements in a list by a key:
    var groups = people.GroupBy(p => p.Age);
    
  15. Combine elements of two lists using a function:
    List<int> combinedList = list1.Zip(list2, (x, y) => x + y).ToList();
    
  16. Take the first "n" elements from a list:
    List<int> firstNElements = numbers.Take(3).ToList();
    
  17. Skip the first "n" elements of a list:
    List<int> remainingElements = numbers.Skip(3).ToList();
    
  18. Partition a list into fixed-sized groups:
    List<List<int>> groups = numbers.Select((x, i) => new { Index = i, Value = x })
                                     .GroupBy(x => x.Index / 3)
                                     .Select(g => g.Select(x => x.Value).ToList())
                                     .ToList();
    
  19. Find the index of the first element that matches a given condition:
    int index = numbers.FindIndex(x => x == 42);
    
  20. Convert a list of strings to a single string:
    string result = string.Join(", ", strings);
    
  21. Remove elements from a list that match a given condition:
    numbers.RemoveAll(x => x % 2 == 0);
    
  22. Convert a list of objects to a list of their property values:
    List<string> names = people.Select(p => p.Name).ToList();
    
  23. Sort a list of objects by a specific property:
    List<Person> sortedPeople = people.OrderBy(p => p.Age).ToList();
    
  24. Sort a list of objects by multiple properties:
    List<Person> sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();
    
  25. Create a list of objects from two lists with corresponding elements:
    List<Tuple<int, string>> pairedList = list1.Zip(list2, (x, y) => Tuple.Create(x, y)).ToList();
    
  26. Flatten a list of lists into a single list:
    List<int> flattenedList = listOfLists.SelectMany(x => x).ToList();
    

Conclusion

Lambda expressions in C# offer a powerful and expressive way to work with lists, using lambda expressions in conjunction with various list operations, developers can write more concise and readable code. This article has provided an overview of some common list operations and demonstrated how to use lambda expressions to perform them, along with more than 26 code samples to illustrate their usage.

Let's learn more about Lambda expression from our other articles! You will find multiple articles to learn Lambda expression further.