C#处理集合中项目检查的优雅方式

JL.*_*JL. 1 c#

我在下面发布了一个代码示例.首先让我解释一下

下面代码中的termStore.Groups是一组Group Objects(确切的类是无关紧要的).

检查null:if(termStore.Groups [groupName] == null)似乎是一种逻辑(干净)方法,但如果Groups集合为空,则会产生异常.

使用termStore.Groups.Contains也不是一个选项,因为这需要一个强类型,即:.Contains(Group)... not .Contains(GroupName as string)

有人可以推荐一种干净/通用的方式,我可以检查一个项目是否存在于集合中.

谢谢....

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

更新:确切的类Sharepoint分类类.http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

更新2,确切的集合:http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Iai*_*way 8

Microsoft.SharePoint.Taxonomy.GroupCollection实现IEnumerable<Group>,所以LINQ可能正是医生所要求的: -

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.
}
Run Code Online (Sandbox Code Playgroud)

您需要使用.NET 3.5或更高版本并添加"using System.Linq;" 到文件的顶部.

编辑

如果您没有可用的LINQ,或者它冒犯了您,或者您真的已经分析过,并且发现与字符串索引器相比,迭代组会破坏性能,您可以使用GroupCollection.Count来避免错误状态: -

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