如何使用“包含”在列表中

本文关键字:列表 包含 何使用 | 更新日期: 2023-09-27 18:10:14

我有国家数据库点赞,

Country
-------
England
Germany
Italy
...

我得到这个数据源为

   DB.Countries.ToList();

我要做的是检查新添加的国家是否已经存在,
只是喜欢,

if(DB.Countries.ToList().Contains(newAddedCountry))
{
 ..............
}

但是我不知道如何将newAddedCountry (string)转换为System.Collections.Generic.List<Country>

如何使用“包含”在列表中

if(DB.Countries.Any(c => c.Country == newAddedCountry))
{
    // exists ..
}

可以使用Enumerable.Any方法;

确定一个序列是否包含任何元素。

if( DB.Countries.Any( n => n.Country == newAddedCountry ))

试试这样

if(DB.Countries.Any(c => c.CountryName == newAddedCountry.CountryName ))
{
    // exists ..
}

您可以将国家名称与Country类中的属性进行比较。比如:

if(DB.Countries.ToList().Any(r=> r.Name == newAddedCountry))
                                 ^^^^^^
                                 Field/Property name holding the Name of Country

如果你想比较忽略大小写的字符串,那么:

if(DB.Countries.ToList()
               .Any(r=> r.Name.Equals(newAddedCountry, StringComparison.InvariantCultureIgnoreCase))

使用Country类的属性可能更容易,就像这样:

if (db.Countries.Select(x => x.Name).ToList().Contains(countryName))
{
    ...
}

if (db.Countries.Any(x => x.Name == countryName))
{
    ...
}

Country为列名:

if(DB.Countries.ToList().Any(c => c.Country == newAddedCountry))
{ 
    //Do something
}

如果我没记错的话,contains使用Equals方法来比较实例。所以你需要在你的国家类中实现一个Equals重写方法。你试图比较字符串和国家对象实例,所以它们当然不能被正确比较。

我想试试LINQ解决方案:

List<Country> countries = DB.Countries.ToList();
if (countries.Any(x => x.column == newAddedCountry)) {
    ...
}

x == newAddedCountry,如果它只是一个列表。