Izzy
Izzy

Reputation: 6866

Comparing string is not working as expected

Consider the following code snippet.

var query = (from a in db.MyEntity
                         where a.MyEntityId == id
                         select a.Team).FirstOrDefault();

string userName = userDto.UserName.Replace('.', ' ');
string[] teamArray = query.Split(new char[] { ',' });

for (int i = 0; i < teamArray.Count(); i++)
{
   if (!teamArray[i].Contains(userName, StringComparison.OrdinalIgnoreCase))
      {
         return View("Unauthorized");
      }
}

I have a column in a database which has , separated values inside it i.e.

User 1, User 2, User 3 ...

I do not have control on how many users that go in this column. What I'm trying to achieve is to display an Unauthorized page to any user that's not in that column. I get the username of the logged in person using HttpContext.Current.User.Identity.Name.Split('\\')[1]; For testing purpose I've put my user name in the column along with another but it seems to be checking every single username and then returning me the Unauthorized which it shouldn't do because my username is in the column. Can someone tell me where I'm going wrong please.

Below is the extension method I'm using

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
   return source.IndexOf(toCheck, comp) >= 0;
}

Upvotes: 1

Views: 100

Answers (2)

Manoranjan
Manoranjan

Reputation: 1

See below :

public static bool Contains(string source, string toCheck)
{
    var results = Array.FindAll(source.split(','), s => s.Equals(toCheck));
    if(results.Length > 0)
        return true;
    else
        return false;
}

Thank you.

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

but it seems to be checking every single username

Yes, that is exactly what you do here

string[] teamArray = query.Split(new char[] { ',' });

for (int i = 0; i < teamArray.Count(); i++)
{
   if (!teamArray[i].Contains(userName, StringComparison.OrdinalIgnoreCase))
   {
       return View("Unauthorized");
   }
}

You call your Contains method for every single string in the teamArray. And since your userName will only match one (if any), all the others will return you the error.

It seems you confused two things. You want to check if any of the strings in teamArray matches userName:

string[] teamArray = query.Split(new char[] { ',' });
if (!teamArray.Contains(userName, StringComparer.OrdinalIgnoreCase))
    return View("Unauthorized");

So use this teamArray.Contains(...) to check if userName is inside your teamArray.

Upvotes: 2

Related Questions