Home > Mobile >  How to check if a context request path starts with a given string from a list of strings?
How to check if a context request path starts with a given string from a list of strings?

Time:09-30

I have multiple if statements here which would check if a request path starts with a given string and return true if the condition is met

if (context.Request.Path.StartsWithSegments("/abc/def", StringComparison.OrdinalIgnoreCase))
 {  return true; }
if (context.Request.Path.StartsWithSegments("/pqr/xyz", StringComparison.OrdinalIgnoreCase))
 {  return true; }
       

and so on with few more if statements....

How do I optimize this and create a list of such values ("/abc/def") where it would just iterate through the list and return true if the condition is met?

CodePudding user response:

You can use .Any() with the list of expected path,

var expectedPath = new List<string>(){"/abc/def", "/pqr/xyz"};

return expectedPath.Any(x => context.Request.Path.StartsWithSegments(x, StringComparison.OrdinalIgnoreCase));

CodePudding user response:

You can Use Array.Exists() method for checking path is expectedPath array.

    string[] expectedPath = {"/abc/def", "/pqr/xyz"};
    Console.WriteLine(Array.Exists(expectedPath, element => emlement == StringComparison.OrdinalIgnoreCase);
    Console.WriteLine(Array.Exists(expectedPath, element => element =="/abc/def")); // this will return true
    Console.WriteLine(Array.Exists(expectedPath, element => element =="A")); //this is return false
  • Related