zey
zey

Reputation: 6103

How to use "Contain" in List?

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

Answers (7)

Satpal
Satpal

Reputation: 133403

Assuming Country as column name:

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

Upvotes: 1

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

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

Jurijs Kastanovs
Jurijs Kastanovs

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

Roy Dictus
Roy Dictus

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

vborutenko
vborutenko

Reputation: 4443

Try something like this

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

Upvotes: 4

Habib
Habib

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

Tim Schmelter
Tim Schmelter

Reputation: 460108

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

Upvotes: 14

Related Questions