1

I have a List which contains the list of words that needs to be excluded.

My approach is to have a List which contains these words and use Linq to search.

List<string> lstExcludeLibs = new List<string>() { "CONFIG", "BOARDSUPPORTPACKAGE", "COMMONINTERFACE", ".H", };
string strSearch = "BoardSupportPackageSamsung";
bool has = lstExcludeLibs.Any(cus => lstExcludeLibs.Contains(strSearch.ToUpper()));

I want to find out part of the string strSearch is present in the lstExcludedLibs.

It turns out that .any looks only for exact match. Is there any possibilities of using like or wildcard search

Is this possible in linq?

I could have achieved it using a foreach and contains but I wanted to use LINQ to make it simpler.

Edit: I tried List.Contains but it also doesn't seem to work

Gray
  • 7,050
  • 2
  • 29
  • 52
KK99
  • 1,971
  • 7
  • 31
  • 64

3 Answers3

5

You've got it the wrong way round, it should be:-

List<string> lstExcludeLibs = new List<string>() { "CONFIG", "BOARDSUPPORTPACKAGE", "COMMONINTERFACE", ".H", };
string strSearch = "BoardSupportPackageSamsung";
bool has = lstExcludeLibs.Any(cus => strSearch.ToUpper().Contains(cus));

Btw - this is just an observation but, IMHO, your variable name prefixes 'lst' and 'str' should be ommitted. This is a mis-interpretation of Hungarian notation and is redundant.

Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
1

I think the line should be:

bool has = lstExcludeLibs.Any(cus => cus.Contains(strSearch.ToUpper()));
ysrb
  • 6,693
  • 2
  • 29
  • 30
  • With my example, i always get false with your suggestion. i am searching if `BoardSupportPackage` in `BoardSupportPackageSamsung`. Generally Contains should work, but i get false – KK99 Jul 12 '11 at 06:18
  • Try changing it: bool has = lstExcludeLibs.Any(cus => strSearch.ToUpper().Contains(cus)); – ysrb Jul 12 '11 at 06:19
  • `ToUpper` and `ToLower` are common tricks, but a bad idea if you ever want to support any language but English. See this question for a better solution than `ToUpper`: http://stackoverflow.com/questions/444798/case-insensitive-containsstring – Merlyn Morgan-Graham Jul 12 '11 at 06:20
  • 1
    Nitpicking.Example code fails under Turkish locale. Uppercase of Config is CONFİG and therefore it does not match. Using `ToUpperInvariant()` is a better choice. – idursun Jul 12 '11 at 06:20
1

Is this useful to you ?

bool has = lstExcludeLibs.Any(cus => strSearch.ToUpper().Contains(cus));

OR

bool has = lstExcludeLibs.Where(cus => strSearch.ToUpper().IndexOf(cus) > -1).Count() > 0;

OR

bool has = lstExcludeLibs.Count(cus => strSearch.ToUpper().IndexOf(cus) > -1) > 0;
shenhengbin
  • 4,236
  • 1
  • 24
  • 33