Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to access/call list collection items for method GetCapital()?
namespace WindowsPhoneApplication1
{
public class Countries : List<myword>
{


public Countries()
{ 
myWord latvia = new myWord("Latvia");
latvia.Capital = "Riga";
latvia.area = "65 000 sq. km";
this.Add(latvia);
myWord lithuania = new myWord("Lithuania");

lithuania.Capital = "Vilnius";
lithuania.area = "65 000 sq. km"; 
this.Add(lithuania); 
}
public string GetCapital(string theWord)
{ 
//HERE I WANT TO CALL THE ITEM E.G Latvia to get the capital using parameter which is the countryname or the listitem

string a=new myWord(theWord).Capital;
//this line above is what i tried to do but I think with this I was creating a new instance so string a returns null
return (a);
}
}

public class myWord
{
  public myWord(string name)
  {
     this.countryName = name;
  }
  public string countryName { get; set; }
  public string Capital { get; set; }
  public string area { get; set; }
}
}
</myword>

see GetCapital()

I want to get the capital using variable countryName that I will use as parameter?
Posted
Updated 22-Aug-10 3:12am
v2

1 solution

If it were me, I'd create a class derived from List, and write accessor functions that used LINQ to find what you want.

public class MyList : List<MyWord>
{
    public MyWord ByCapitol(string capitol)
    {
        var country = (from item in this 
                       where item.Capitol == capitol 
                       select item).First();
        return (MyWord)country;
    }
}

And so on. BTW, your object initialization can go a lot smoother if you do something like this:

MyList myList = new MyList();
myList.Add(new MyWord(){CountryName="USA", 
                        Capitol="Washington, DC", 
                        Area="Some area info"});


You should also change your constructor and add another:

public class MyWord
{
    public MyWord() {};
    public MyWord(string name, string capitol, string area)
    {
        this.CountryName = name;
        this.Capitol = capitol;
        this.Area = area;
    }
}


That makes your oject much more versatile with regards to initialization.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900