Removing Duplicate SPList Objects From Typed Collections
One of my friends had a slight dilemma in his code this morning where he had a recursive loop, subject and constrained by some limit logic, which iterated through SPList objects in an arbitrary SPWeb and returned a large typed collection of SPList objects. The collection was afterward used for massaging out some specific SPField values, assimilated later by a detached business application.
One difficulty that he was running into was the occurrence of duplicates that were taking place during the generation of the collection. He was questioning if it was workable to inspect and eliminate duplicate SPList objects that occur before returning the final SPList collection.
In order to do this, we of course necessitate a unique identifier for each object, so it makes sense to use the SharePoint generated SPList.ID property which guarantees a unique value. Within the method, we are creating two other collections, a temporary typed dictionary object which will hold the ID values to later act as a guard clause, as well as a provisional SPList collection which will provide return allocation.
- public static List<SPList> CheckAndRemoveDuplicateSPList(IEnumerable<SPList> inputList)
- {
- Dictionary<Guid, int> tempDictonary = new Dictionary<Guid, int>();
- List<SPList> tempListCollection = new List<SPList>();
- foreach (SPList list in inputList)
- {
- if (!tempDictonary.ContainsKey(list.ID))
- {
- tempDictonary.Add(list.ID, 0);
- tempListCollection.Add(list);
- }
- }
- return tempListCollection;
- }
That should do the trick!
:)
One Comment
Trackbacks/Pingbacks
- Links (7/8/2008) « Steve Pietrek - Everything SharePoint - [...] Removing Duplicate SPList Objects From Typed Collections [...]
- FuzzLinks.com » SharePoint Shelter » Blog Archive » Removing Duplicate SPList Objects From Typed Collections - [...] http://www.sharepointsecurity.com/blog/sharepoint/sharepoint-2007-development/removing-duplicate-splist-objects-from-typed-collections/ [...]
Articles & Research
SharePoint Security
SharePoint Development
SharePoint Architecture
Claims Authentication
Forefront For SharePoint
AIS / Dynamics GP
Team Foundation Server
Pex And Moles
ISA/TMG/IAG/UAG
DPM
Cardspace
Research Methodology
Rural ICT Development
Numerical Analysis
Multi-Level Research
Knowledge Management
Personal/Off-Topic
GroupBy makes this trivial:
return from l in inputList
group l by l.ID into g
select g.First();
Or in code:
return inputList.GroupBy(l => l.ID).Select(g => g.First());