开发者

LINQ If .Any matches .Any

I have 2 string arrays, and I would like to return if any of them exists in _authRole array. How is that done?

 string[] _userRoles = userdata.Split(',');

 string[] _authRoles = AuthRoles.Split(',');


 bool isAuthorized = _authRoles.Any(_userRoles ??开发者_StackOverflow社区);

/M


If what you want is to determine if _authRoles and _userRoles have at least one common item, then use:

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

You can also query the result of Intersect in any other way you choose.


Try this:

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


Suppose the lists are of size N and M and that the likely scenario is no 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 could be written more clearly as Jon's solution.

Another solution which is basically the same as Adam and Jon's would be to join the two lists:

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

That's a bit heavier weight than necessary but it reads nicely. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜