繁体   English   中英

如何搜索类类型的列表属性

[英]How to search list property of class type

我有一个叫做capital的类,其中包含2个变量country和capital。

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

我有上述类别类型的列表,即List<country>我可以使用国家/地区类别变量添加值。 现在如何查找特定值,例如列表包含这些值

country:USA,
capital:New York    

country:China,
capital:Bejing

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

使用.Find() 使用Linq Extension方法将需要您引用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; }
    }
}

最简单的方法是使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM