user15923090
user15923090

Reputation:

How to check whether any input word is found in a given list

public static bool isExactLocation(string item)
{
    Boolean isLocation = false;
    String[] LocationcheckList = File.ReadAllLines(@"C:\list\LocationCheckList");
    List<string> LocationList = new List<string>();
    foreach (String words in LocationcheckList)
    {
        String Words = words.ToLower().Trim();
        LocationList.Add(Words);
    }
    String input = item.ToLower().Trim();
    foreach (string value in LocationList)
    {
        if (input.Equals(value))
        {
            isLocation = true;
            break;
        }
    }
    return isLocation;    
}

My location list has these values:

My question when I give input as "Saudi Arabia" it should take each word in input and compare with the location list if any one the word is present in the list it should give true and that too only using equals method.

Upvotes: 0

Views: 155

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

First of all, let's read the file just once:

   using System.Linq;

   ... 

   // HashSet.Contains is faster then List.Contains: O(1) vs. V(N) 
   private static HashSet<string> s_Words = new HashSet<string>(File
     .ReadLines(@"C:\list\LocationCheckList")
     .Where(line => !string.IsNullOrWhiteSpace(line))
     .Select(item => item.Trim()), 
        StringComparer.OrdinalIgnoreCase
   );

then you can easily check:

   public static bool isExactLocation(string item) {
     return item
       ?.Split(' ', StringSplitOptions.RemoveEmptyEntries)
       ?.All(word => s_Words.Contains(word)) ?? null;
   } 

Edit: if you insist on List<strint> and for (foreach) loop:

   private static List<string> s_Words = File
     .ReadLines(@"C:\list\LocationCheckList")
     .Where(line => !string.IsNullOrWhiteSpace(line))
     .Select(item => item.Trim())
     .ToList();

then we can loop...

   public static bool isExactLocation(string item) {
     if (null == item)
       return false;

     string[] words = item
       .Split(' ', StringSplitOptions.RemoveEmptyEntries);

     foreach (string word in words) {
       bool found = false;

       foreach (string location in s_Words) {
         if (location.Equals(word, StringComparison.OrdinalIgnoreCase)) {
           found = true;

           break;  
         } 
       }

       if (!found)
         return false;
     }   

     return true;  
  } 

Upvotes: 1

Zahir J
Zahir J

Reputation: 1179

You can do something like


    using System.Linq;
    LocationCheckList.Any(x=> item.Split(' ').Contains(x))

but watch out for "South Korea vs South Africa"

Upvotes: 1

Related Questions