Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# list
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 22-Aug-10 4:06am
gherard543
Edited 22-Aug-10 4:12am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
v3

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

  Print Answers RSS
0 OriginalGriff 587
1 Sergey Alexandrovich Kryukov 479
2 Maciej Los 305
3 BillWoodruff 220
4 Mathew Soji 195
0 OriginalGriff 7,356
1 Sergey Alexandrovich Kryukov 6,817
2 DamithSL 5,461
3 Manas Bhardwaj 4,946
4 Maciej Los 4,475


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 22 Aug 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100