在我的方法上访问列表集合的简单问题 [英] simple problem accessing list collection on my method
本文介绍了在我的方法上访问列表集合的简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何访问/调用方法GetCapital()
的列表收集项?
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>
参见GetCapital()
我想使用将用作参数的变量countryName来获得资本吗?
see GetCapital()
I want to get the capital using variable countryName that I will use as parameter?
推荐答案
如果是我,我将创建一个从List
派生的类,并编写使用LINQ查找所需内容的访问器函数.
If it were me, I''d create a class derived fromList
, 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.
这篇关于在我的方法上访问列表集合的简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文