我在下面发布了代码示例。首先让我解释一下
以下代码中的termStore.Groups是组对象的集合(确切的类无关紧要)。
检查null:如果(termStore.Groups [groupName] == null)看起来像是一种逻辑(干净)方法,但是如果Groups集合为空,则会产生异常。
使用termStore.Groups.Contains也不是一种选择,因为这需要强类型,即:.Contains(Group)...不是.Contains(GroupName as string)
有人可以推荐一种干净/通用的方式来检查项目是否存在于集合中。
谢谢....
TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
if (termStore.Groups[groupName] == null)
{
termStore.CreateGroup(groupName);
termStore.CommitAll();
}
更新:确切的类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
请您参考如下方法:
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.
}
您需要使用.NET 3.5或更高版本,并添加“ using System.Linq;”。到文件顶部。
编辑
如果您没有可用的LINQ,或者如果它冒犯了您,或者如果您确实进行了分析并发现与字符串索引器相比,遍历Groups会降低性能,则可以使用GroupCollection.Count来避免出现错误状态:-
if (termStore.Groups.Count == 0 || termStore.Groups[groupName] == null)
{
// Group doesn't exist.
}
