tags:

views:

96

answers:

4

I have to search a list of strings in CityList and if it contains all search strings then it should return true otherwise false.

When i search "London","Dallas" against CityList it should return false,because "Dallas" is missing in CityList.

var CityList=new string[] { "London","Paris","Houston","Mexico","Budapest"}

var search =new string[] {"London","Dallas"};

How to rewrite the following ?

var result =  CityList.Select(c => c).ToList().FindAll(search.ToArray());
+4  A: 

Try the following:

var hasAll = !search.Except(CityList).Any();

By the way, you should never write something.Select(c => c); such a statement will do nothing but make the program a tiny bit slower.

SLaks
That's the correct answer, but the other way round (it returns false if some terms of search is in the CityList, and true otherwise). So : ! search.Except(CityList).Any();
Yann Schwartz
Fixed; thank you.
SLaks
return something.Select(c => c); is very useful when you want to return an IEnumerable from a List, Collection whatever without returning the actual object. I use it all the time.
AZ
@AZ: That's what the `AsEnumerable` method is for. http://msdn.microsoft.com/en-us/library/bb335435.aspx
SLaks
+2  A: 

That quite an easy one

search.All(c => CityList.Contains(c))

All will only satify when all predicates return true, then we check if the citylist contains the item

almog.ori
My way is faster, since `Except` will build a hash table.
SLaks
Where do you get that?
almog.ori
Reflector (Beta)
SLaks
SLaks' way also uses more memory, since Except will build a hash table. The speed increase does not come for free; it trades more memory for less time. Since memory is generally a cheaper resource than time, this is probably a good tradeoff. But it's worth remembering that performance optimizations usually involve trading one kind of bad performance for another.
Eric Lippert
+3  A: 

Try this:

var result = search.All(s => CityList.Contains(s));
Anders Fjeldstad
+3  A: 

You have various possibilities:

var result = CityList.Union(search).Count() == CityList.Count();
var result2 = search.All(s => CityList.Contains(s));
var result3 = search.ToList().TrueForAll(s => CityList.Contains(s));
var result4 = CityList.Intersect(search).Count() == search.Count();
klausbyskov
The first method won't work if `CityList` has duplicate elements.
SLaks