user603007 user603007 - 1 year ago 117
C# Question

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

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


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>();

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; }

Answer Source

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")

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.

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