Reputation: 6103
I have country database likes ,
Country
-------
England
Germany
Italy
...
I get this data source as ,
DB.Countries.ToList();
What I want to do is to check new added country is already exists or not ,
just likes ,
if(DB.Countries.ToList().Contains(newAddedCountry))
{
..............
}
But I don't know how to convert newAddedCountry
(string) to System.Collections.Generic.List<Country>
.
Upvotes: 6
Views: 1817
Reputation: 133403
Assuming Country
as column name:
if(DB.Countries.ToList().Any(c => c.Country == newAddedCountry))
{
//Do something
}
Upvotes: 1
Reputation: 98750
You can use Enumerable.Any
method;
Determines whether a sequence contains any elements.
if( DB.Countries.Any( n => n.Country == newAddedCountry ))
Upvotes: 6
Reputation: 685
If I remember this right, contains uses Equals method to compare instances. So you'd need to implement a Equals override method in your Countries class. And in any way - you are trying to compare String and Countries object instance, so ofcourse they don't get to be compared properly.
I'd try going for LINQ solution:
List<Country> countries = DB.Countries.ToList();
if (countries.Any(x => x.column == newAddedCountry)) {
...
}
or x == newAddedCountry
if it's just a List.
Upvotes: 0
Reputation: 33139
It's probably easier to just use a property of your Country
class instead, like so:
if (db.Countries.Select(x => x.Name).ToList().Contains(countryName))
{
...
}
or
if (db.Countries.Any(x => x.Name == countryName))
{
...
}
which is more efficient.
Upvotes: 1
Reputation: 4443
Try something like this
if(DB.Countries.Any(c => c.CountryName == newAddedCountry.CountryName ))
{
// exists ..
}
Upvotes: 4
Reputation: 223247
You can compare the Name of the country against your property in Country
class. Something like:
if(DB.Countries.ToList().Any(r=> r.Name == newAddedCountry))
^^^^^^
Field/Property name holding the Name of Country
if you want to compare string ignoring case then:
if(DB.Countries.ToList()
.Any(r=> r.Name.Equals(newAddedCountry, StringComparison.InvariantCultureIgnoreCase))
Upvotes: 2
Reputation: 460108
if(DB.Countries.Any(c => c.Country == newAddedCountry))
{
// exists ..
}
Upvotes: 14