1

For example the list lstHazProduct contains items like "NOTEBOOK LAPTOP", "MOBILE PHONE".

strTest = "SAMSUNG NOTEBOOK";

How to use linq or %LIKE% operator.

If the list items exist in the string, then condition met. Below doesn't work as it compare the string to the list items.

if (lstHazProducts.Where(s => s.HazpName.Contains(strTest)).Count() > 0)
{
 //do something
}

Thanks.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
JL_Coder
  • 152
  • 1
  • 4
  • 12

2 Answers2

3

Your code is enough to check for matching items of lstHazProducts with strTest similar to %Like%. But that is not enough to perform a search for check for items in the list that contains any words in the strTest. You can use the following code in that case:

var searchParams = strTest.Split(' ');
if (lstHazProducts.Count(s => searchParams.Any(s.HazpName.Contains)) > 0)
{
   //do something
}

As an alternative for Count()>0 you can try Any() like the following:

if (lstHazProducts.Any(s => searchParams.Any(s.HazpName.Contains)))
{
   //do something
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

First of all let's agree with condiotion(s). So far, so good you have

string strTest = "SAMSUNG NOTEBOOK";

It seems that you what to check if any word (SAMSUNG, NOTEBOOK) is in the string, if it's your case:

// In case strTest is long, HashSet<T> is the most efficient structure  
HashSet<String> terms = new HashSet<String>(strTest.Split(
    new char[] { ' ' }, 
    StringSplitOptions.RemoveEmptyEntries), // to prevent double space false positive
  StringComparer.OrdinalIgnoreCase);        // let be nice and allow "NoteBook"

...

List<String> lstHazProduct = new List<String>() {
  "NOTEBOOK LAPTOP", 
  "MOBILE PHONE", 
};

var result = lstHazProduct
  .Where(line => line
     .Split(new char[] { ' ' })
     .Any(item => terms.Contains(item)))
  .ToArray(); // let's materialize the result into an array 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215