C# Elegant way to handle checking for an item in a collection.

Posted by JL on Stack Overflow See other posts from Stack Overflow or by JL
Published on 2010-12-21T10:41:41Z Indexed on 2010/12/21 10:54 UTC
Read the original article Hit count: 202

Filed under:

I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

© Stack Overflow or respective owner

Related posts about c#