Filtering on template list with property name as string

前端 未结 4 1505
灰色年华
灰色年华 2021-01-16 06:26

Hi I have to apply filter on generic class. The sample class is as follows

public class Sample
{
    List sourceList = new List();         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-16 07:00

    Here I give you a sample example how to implement filtering using LINQ on List items..

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

    Now, lets create a list of objects based on class clsCountry and store them in a List object.

    List lstCountry = new List();
    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 object lstCountry to a DropDownList control named drpCountry as like as:

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

    Now, use LINQ to filter data from the lstCountry object and bind the filtered list to the dropdown control drpCountry.

     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

    Now apply those techniques on your case..

提交回复
热议问题