开发者

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

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 cl开发者_运维百科ass 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

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx


Microsoft.SharePoint.Taxonomy.GroupCollection implements IEnumerable<Group>, so a bit of LINQ is probably just what the doctor ordered:-

if(termStore.Groups.Any(x => x.Name == "MyGroup"))
{
   // group contains at least one item matching the predicate.
}
else
{
   // group contains no items matching the predicate.
}

You'll need to be using .NET 3.5 or better and add "using System.Linq;" to the top of your file.

Edit

If you don't have LINQ available, or if it offends you, or if you've genuinely profiled and found that iterating over Groups is killing performance compared to the string indexer, you could use GroupCollection.Count to avoid the error state:-

if (termStore.Groups.Count == 0 || termStore.Groups[groupName] == null)
{
  // Group doesn't exist.
}


IEnumerable.Any(...) should work for your case:

termsStore.Groups.Any()


I think this is what you are looking for:

termStore.Groups.ContainsKey(groupName)

Checks that the key exists, doesn't throw an exception if it doesn't. This is assuming that Groups is a collection that implements IDictionary.


May be this

termStore.Any() && termStore.Groups.Any() && termStore.Groups[groupName] == null


Ok, 2nd attempt. If Groups doesn't contain the required ContainsKey method then you can write it yourself. Then you can just use ContainsKey in place of Contains.

static class GroupExtensions
{
   public static bool ContainsKey(this Groups groups, string key) 
   {
      try
      {
         if(groups[key] == null)
         {
            return false;
         }
      }
      catch
      {
         return false;
      }
      return true;
   }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜