LINQ If .Any fits. Any

I have 2 string arrays and I would like to return if any of them exist in the _authRole array. How it's done?

string[] _userRoles = userdata.Split(','); string[] _authRoles = AuthRoles.Split(','); bool isAuthorized = _authRoles.Any(_userRoles ??); 

/ M

+4
source share
3 answers

Try the following:

 Boolean isAuthorized = _userRoles.Any(user => _authRoles.Contains(user)); 
+7
source

If you want to determine if _authRoles and _userRoles at least one common element, use:

 bool isAuthorized = _authRoles.Intersect(_userRoles).Any(); 

You can also request an Intersect result in any other way that you choose.

+10
source

Suppose the lists are N and M in size and that the likely scenario does not match. Andrew's solution is O (NM) in time and O (1) in extra memory. Adam's solution is O (N + M) in time and memory, but can be written more clearly as John's solution.

Another solution, which basically coincides with Adam and John, would be to combine the two lists:

 var joined = from user in userRoles join auth in authRoles on user equals auth select user; return joined.Any(); 

It's a little harder than necessary, but it reads well. :-)

+3
source

Source: https://habr.com/ru/post/1309430/


All Articles