filter a list of custom objects in csharp

In C#, we can use LINQ to filter a list of custom objects based on specific conditions. Here's an example:

Suppose we have a custom class called Person defined as follows:

main.cs
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
94 chars
6 lines

and we have a list of Person objects:

main.cs
var people = new List<Person>
{
    new Person { Name = "John", Age = 25 },
    new Person { Name = "Jane", Age = 30 },
    new Person { Name = "Bob", Age = 20 },
    new Person { Name = "Alice", Age = 35 }
};
210 chars
8 lines

To filter this list to only include people whose age is greater than or equal to 30, we can use LINQ's Where method as follows:

main.cs
var filteredPeople = people.Where(p => p.Age >= 30);
53 chars
2 lines

This will return a new IEnumerable<Person> containing only the Person objects whose age is greater than or equal to 30.

We can then iterate over the filtered list to perform further operations on the objects, or simply return it if that is all that is needed.

gistlibby LogSnag