Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a list in C# with lambda expression?

Tags:

I am trying to filter a list so it results in a list with just the brisbane suburb?

c#

Temp t1 = new Temp() { propertyaddress = "1 russel street",  suburb = "brisbane" };
            Temp t2 = new Temp() { propertyaddress = "12 bret street", suburb = "sydney" };
            List<Temp> tlist = new List<Temp>();
            tlist.Add(t1);
            tlist.Add(t2);

            List<Temp> tlistFiltered = new List<Temp>();
            //tlistFiltered. how to filter this so the result is just the suburbs from brisbane?

public class Temp
    {
        public string propertyaddress { get; set; }
        public string suburb { get; set; }
    }
like image 944
user603007 Avatar asked Mar 21 '12 05:03

user603007


People also ask

How to filter in list C#?

C# filter list with iteration. In the first example, we use a foreach loop to filter a list. var words = new List<string> { "sky", "rock", "forest", "new", "falcon", "jewelry" }; var filtered = new List<string>(); foreach (var word in words) { if (word. Length == 3) { filtered.

Can you have a list in a list C#?

List, nested. A List can have elements of List type. This is a jagged list, similar in syntax to a jagged array. Lists are not by default multidimensional in C#.


1 Answers

Use Where clause to filter a sequence

 var tlistFiltered = tlist.Where(item => item.suburb == "brisbane")

LINQ expressions like Where return IEnumerable<T>. I usually capture the result with var but you could use ToList() to project the result to a list as well. Just depends what you need to do with the list later.

List<Temp> tlistFiltered = tlist
    .Where(item => item.suburb == "brisbane")
    .ToList()

Note that with the above you don't have to allocate a new list. The Where and ToList() methods both return a new sequence which you just need to capture with the reference.

like image 96
Despertar Avatar answered Sep 29 '22 08:09

Despertar