views:

401

answers:

3

I've got some code that creates a list of AD groups that the user is a member of, with the intention of saying 'if user is a member of GroupX then allow admin access, if not allow basic access'.

I was using a StringCollection to store this list of Groups, and intended to use the Contains method to test for membership of my admin group, but the problem is that this method only compares the full string - but my AD groups values are formatted as cn=GroupX, etc....

I want to be easily able to determine if a particular substring (i.e. 'GroupX') appears in the list of groups. I could always iterate through the groups check each for a substring representing my AD group name, but I'm more interested in finding out if there is a 'better' way.

Clearly there are a number of repositories for the list of Groups, and it appears that Generics (List(Of String)) are more commonly preferred (which I may well implement anyway) but there is no in-built means of checking for a substring using this method either.

Any suggestions? Or should I just iterated through the list of groups?

RESULT:

I've settled on using a List(Of), and I've borrowed from Dan's code to iterate through the list.

+1  A: 

Writing a helper function which will iterate through the items checking for substrings and returning you a Boolean flag seem to be your best bet.

NimsDotNet
Thats what I'm doing in the meantime, and it's not a big deal... but I'm just curious about alternatives, if there are any - you can't have too many options!
CJM
A: 

You can use a predicate function for that. It's a boolean function which will help you to filter out some entries.

For example, to get non-hidden files from a list:

Public ReadOnly Property NotHiddenFiles As List(Of FileInfo)

    Get
        Dim filesDirInfo As New DirectoryInfo(FileStorageDirectory)
        Return filesDirInfo.GetFiles.ToList.FindAll(AddressOf NotHiddenPredicate)
    End Get

End Property



Private Function NotHiddenPredicate(ByVal f As FileInfo) As Boolean

    Return Not ((f.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden)

End Function
Sphynx
+2  A: 

I don't think you're going to find a better method than enumerating over the collection*.

That said, here's a good way to do it that will be independent of collection type:

Public Function ContainsSubstring(ByVal objects As IEnumerable, ByVal substring As String) As Boolean
    Dim strings = objects.OfType(Of String)()
    For Each str As String in strings
        If str.Contains(substring) Then Return True
    Next

    Return False
End Function

This is a good way to address the "which collection to use?" issue since basically all collections, generic or not (ArrayList, List(Of String), etc.), implement IEnumerable.

*Justification for why I believe this forthcoming.

Dan Tao
+1 for flexible solution, inc. code sample (always welcome).
CJM