skip to Main Content

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?

2

Answers


  1. 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));
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search