Using Linq to Filter a list

So yesterday I made this post on applying a filter or map on a list.  Now let’s have a look at how we can do this with Linq.

First the list:

List<string> list = new List<string>();


list.Add("Anne");


list.Add("Brian");


list.Add("Pieter");


list.Add("Wayne");


list.Add("Shane");


list.Add("Susan");


list.Add("Xavier");










Plain old Linq:





// Plain old Linq


var linqFiltered = from item in list


                            where item.StartsWith("S")


                            select item;




Using the Where extension method:







// Linq with the Whete extension method only


var linqListFiltered2 = Enumerable.Where(list, i => i.StartsWith("S"));






And for me the most readable:





// Linq using the Where extension method on the list


var linqListWhereFiltered = list.Where(i => i.StartsWith("S"));






You can even create your own Where method:





static IEnumerable<T> Where<T>(IEnumerable<T> sequence, Func<T, bool> predicate)


{


    foreach (var item in sequence)


        if (predicate(item))


            yield return item;


}






And you can use it like this:





var myLinqListFiltered = Where(list, i => i.StartsWith("S"));





I see so many uses and possibilities for the Linq style code as well as extension methods.

Comments

Popular Posts