Search This Blog

Friday, August 3, 2012

C# Find a value on a given list

Our objective to find the value on a given list. First lets create a class named Country.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication_GridView
{
   public class Country
    {
       private string _cAbs;
       private string _cName;

       public Country(string abs ,string cname)
       {
           _cAbs = abs;
           _cName = cname;
       }

       public string CountryAbreviation
       {
           get { return _cAbs; }
           set { _cAbs = value; }
       }

       public string CountryName
       {
           get { return _cName; }
           set { _cName = value; }
       }
   }

}

In our form.
private void button1_Click(object sender, EventArgs e)
        {
List<Country> countries = new List<Country>();

            countries.Add(new Country("AE", "United Arab Emirates"));
            countries.Add(new Country("AF", "Afghanistan"));
            countries.Add(new Country("AQ", "Antarctica"));
            countries.Add(new Country("AR", "Argentina"));
            countries.Add(new Country("AT", "Austria"));
            countries.Add(new Country("AU", "Australia"));
            countries.Add(new Country("BD", "Bangladesh"));
            countries.Add(new Country("BE", "Belgium"));
            countries.Add(new Country("BR", "Brazil"));
            countries.Add(new Country("BS", "Bahamas"));
            countries.Add(new Country("CA", "Canada"));
            countries.Add(new Country("CH", "Switzerland"));
            countries.Add(new Country("CL", "Chilie"));
            countries.Add(new Country("CM", "Cameroon"));
            countries.Add(new Country("CL", "Chilie"));
            countries.Add(new Country("CN", "China"));
            countries.Add(new Country("CO", "Columbia"));
            countries.Add(new Country("CR", "Costa Rica"));
            countries.Add(new Country("DK", "Denmark"));
            countries.Add(new Country("DM", "Dominica"));
            countries.Add(new Country("DO", "Domican Republic"));
            countries.Add(new Country("EC", "Ecuador"));
            countries.Add(new Country("EE", "Estonia"));
            countries.Add(new Country("EG", "Egypt"));
            countries.Add(new Country("ES", "Spain"));
            countries.Add(new Country("ET", "Ethiopia"));
            countries.Add(new Country("EU", "European Union"));

            Country myCountrySearch = countries.Find(p => p.CountryAbreviation == this.textBox1.Text);

            if (myCountrySearch != null)
            {
                MessageBox.Show("Find one " + myCountrySearch.CountryAbreviation.ToString() + "-"+ myCountrySearch.CountryName.ToString());
            }
            else
            {
                MessageBox.Show("Unable to Find country" + "-" + this.textBox1.Text);
            }
 }

Our Sample Output.



No comments:

Post a Comment