Thursday, April 19, 2012

Filter a List <T> using LINQ


LINQ can be used effectively to filter out a set of objects from a List of objects, in todays post we shall see on how to accomplish object filtering using LINQ.

To know more about binding a List object to a DropDownList refer to the post, Binding a List <T> object to a DropDownList control


First let us create a class whoose objects will be stored in the List <T> here is the code for the class.

public class clsCountry
{
    public string _CountryCode;
    public string _CountryName;
    //
    public clsCountry(string strCode, string strName)
    {
        this._CountryCode = strCode;
        this._CountryName = strName;
    }
    //
    public string CountryCode
    {
        get {return _CountryCode;}
        set {_CountryCode = value;}
    }
    //
    public string CountryName
    {
        get { return _CountryName; }
        set { _CountryName = value; }
    }
}

Next, let us create a list of objects based on our class clsCountry and store them in a List <T> object. Here is the code for the List <T>

List<clsCountry> lstCountry = new List<clsCountry>();
lstCountry.Add(new clsCountry("USA", "United States"));
lstCountry.Add(new clsCountry("UK", "United Kingdom"));
lstCountry.Add(new clsCountry("IND", "India"));

Next, we shall bind the List <T> object lstCountry to a DropDownList control. Here the code to bind the data.

drpCountry.DataSource = lstCountry;
drpCountry.DataValueField = "CountryCode";
drpCountry.DataTextField = "CountryName";
drpCountry.DataBind();

Notice that the DataValueField and DataTextField property of the DropDownList control are mapped to the Properties of the class CountryCode and CountryName, hence make sure to create properties for every member of the class so that they can be used while binding the data to controls.

Finally, we shall use LINQ to filter data from the lstCountry object and bind the filtered list to the dropdown control drpCountry. Here is the code to filter the List <T> using LINQ

var filteredCountries = from c in lstCountry
                        where c.CountryName.StartsWith("U")
                        select c;

drpCountry.DataSource = filteredCountries;
drpCountry.DataValueField = "CountryCode";
drpCountry.DataTextField = "CountryName";
drpCountry.DataBind();

Now the dropdown control will have only 2 items

United States
United Kingdom



Here we are using c.CountryName.StartsWith("U") which works like

CountryName LIKE 'U%' 

We can use c.CountryName.Contains("U"), method to make the filter work like

CountryName LIKE '%U%'

i.e, it will filter out all objects which have the character U anywhere in the CountryName property of the object. 


That’s it we have filtered a List <T> and bound the contents of the filtered List <T> to a DropDownList control.

Search Flipkart Products:
Flipkart.com

No comments: