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

本文关键字:类型 列表 属性 何搜索 搜索 | 更新日期: 2023-09-27 18:15:55

我有一个名为capital的类,它包含2个变量country和capital。这是它的样子…

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

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

country:USA,
capital:New York    
country:China,
capital:Bejing
如何在上面的列表中找到中国…什么是最好的方法呢?

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

使用. find()。使用Linq扩展方法需要引用System.Linq。如果你使用的是。net 3.5及以上版本,这非常棒。否则,只需使用Find.

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);
}