6

我有国家数据库喜欢,

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

我得到这个数据源,

   DB.Countries.ToList();

我想要做的是检查新添加的国家是否已经存在,
就像,

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

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

4

7 回答 7

14
if(DB.Countries.Any(c => c.Country == newAddedCountry))
{
    // exists ..
}
于 2013-04-22T11:09:30.267 回答
6

您可以使用Enumerable.Any方法;

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

if( DB.Countries.Any( n => n.Country == newAddedCountry ))
于 2013-04-22T11:10:07.033 回答
4

尝试这样的事情

if(DB.Countries.Any(c => c.CountryName == newAddedCountry.CountryName ))
{
    // exists ..
}
于 2013-04-22T11:10:38.207 回答
2

您可以在课堂上将国家名称与您的财产进行比较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))
于 2013-04-22T11:10:26.120 回答
1

只使用Country类的属性可能更容易,如下所示:

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

或者

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

哪个更有效率。

于 2013-04-22T11:10:41.353 回答
1

假设Country为列名:

if(DB.Countries.ToList().Any(c => c.Country == newAddedCountry))
{ 
    //Do something
}
于 2013-04-22T11:12:29.537 回答
0

如果我没记错的话, contains 使用 Equals 方法来比较实例。因此,您需要在 Country 类中实现 Equals 覆盖方法。并且以任何方式 - 您正在尝试比较 String 和 Country 对象实例,因此它们当然不会被正确比较。

我会尝试使用 LINQ 解决方案:

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

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

于 2013-04-22T11:13:48.287 回答