Featured post
C# Elegant way to handle checking for an item in a collection -
i've posted code sample below. firstly let me explain
termstore.groups in code below collection of group objects (the exact class irrelevant).
checking null : if (termstore.groups[groupname] == null) seems logical (clean) approach, if groups collection empty exception produced.
using termstore.groups.contains not option either because expects strong type i.e: .contains(group)... not .contains(groupname string)
can recommend clean / generic way can check if 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: exact class sharepoint taxonomy classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx
update 2, exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx
microsoft.sharepoint.taxonomy.groupcollection implements ienumerable<group>, bit of linq doctor ordered:-
if(termstore.groups.any(x => x.name == "mygroup")) { // group contains @ least 1 item matching predicate. } else { // group contains no items matching predicate. }
you'll need using .net 3.5 or better , add "using system.linq;" top of file.
edit
if don't have linq available, or if offends you, or if you've genuinely profiled , found iterating on groups killing performance compared string indexer, use groupcollection.count avoid error state:-
if (termstore.groups.count == 0 || termstore.groups[groupname] == null) { // group doesn't exist. }
- Get link
- X
- Other Apps
Comments
Post a Comment