1

我有一个名为 capital 的类,其中包含 2 个变量 country 和 capital.Here 它看起来如何......

public class country
{
    public string Country { get; set; }
    public string Capital { get; set; }
}

我有一个以上类类型的列表,即List<country>我可以使用国家类变量添加值。现在如何找到包含这些值的列表的特定值

country:USA,
capital:New York    

country:China,
capital:Bejing

如何在上面的列表中找到中国……最好的方法是什么?

4

2 回答 2

3

使用.Find()。使用 Linq 扩展方法将要求您引用 System.Linq。如果您使用的是 .NET 3.5 及更高版本,那就太好了。否则,只需使用查找。

namespace _16828321
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Country> c = new List<Country>()
            {
                new Country(){ Capital = "New York", CountryName = "USA"},
                new Country(){ Capital = "Beijing", CountryName = "China"}
            };

            Country result = c.Find(country => country.CountryName == "China");
        }
    }

    public class Country
    {
        public string CountryName { get; set; }
        public string Capital { get; set; }
    }
}
于 2013-05-30T05:14:47.020 回答
2

最简单的方法是使用 Linq:

var countries = new List<country>();

countries.Add(new country { Country = "USA", Capital = "Washington" });

countries.Add(new country { Country = "China", Capital = "Bejing" });

var usaFromCountries = countries.FirstOrDefault( c => c.Country == "USA" );

if(usaFromCountries == null)
{
   Console.WriteLine("USA did not exist in countries list");
}
else
{
    Console.Write("Capital of the USA is ");
    Console.WriteLine(usaFromCountries.Capital);
}
于 2013-05-30T05:12:38.603 回答