Click here to Skip to main content
Licence CPOL
First Posted 20 Nov 2006
Views 32,814
Bookmarked 26 times

A Set class

By | 20 Nov 2006 | Article
A Set class using a System.Collections.Generic.Dictionary to hold its elements.

Introduction

This class implements a Set using a System.Collections.Generic.Dictionary to hold the elements.

Using the code

The zip file contains three C# files:

  • Set.cs contains the Set class definition.
  • GetTypes.cs contains the static method to get an array of types.
  • SortMode.cs contains the definition of the SortMode enumeration.

To use them, simply add them to your project. The following section describes how to use the class.

Empty instances of Set can be constructed with:

Set<int> a = new Set<int>() ;
Set<char> b = new Set<char>() ;
Set<string> c = new Set<string>() ;

You may construct a Set to contain whatever type of items you require (limited only by the underlying System.Collections.Generic.Dictionary).

Set<object> s = new Set<object>() ;
Set<int[]> s = new Set<int[]>() ;
Set<System.Data.DataRow> s = new Set<System.Data.DataRow>() ;
Set<System.EventHandler> s = new Set<System.EventHandler>() ;
Set<System.Collections.IEnumerable> s = 
       new Set<System.Collections.IEnumerable>() ;

Instances of Set can be constructed and initialized with:

Set<int> s = new Set<int> ( 1 , 2 , 3 ) ;
Set<char> s = new Set<char> ( '1' , '2' , '3' ) ;
Set<string> s = new Set<string> ( "One" , "Two" , "Three" ) ;

Set<int> s = new Set<int> ( somearrayofints ) ;
Set<char> s = new Set<char> ( somearrayofchars ) ;
Set<string> s = new Set<string> ( somearrayofstrings ) ;

Set<int> s = somearrayofints ;
Set<char> s = somearrayofchars ;
Set<string> s = somearrayofstrings ;

The constructor can take any object of type object, but the converters* are somewhat more limited because converting from object or an interface is not allowed.

When an item that is not of the specified type is encountered, it is checked to see if it is IEnumerable, and if so, it will be foreached to recurse across it. This is how the arrays are handled in the above examples. If an object that is neither the target type nor IEnumerable is encountered** an InvalidOperationException is thrown.

Additional converters may be added as needed. And I'll point out that the class is partial so you may put any additional code in a separate file and not modify mine.

* Yes, I realize that having these conversions as implicit goes against the guidelines (because they could fail), but hey, it's my code and I'll do what I want. If you want them to be explicit, define explicit.

** Null items are ignored by default. If throwing NullReferenceExceptions for nulls is desired, define ThrowOnNull.

Once you've constructed instances, you may perform set operations on them:

| or + Union; { 1 , 2 , 3 } | { 2 , 4 , 6 } = { 1 , 2 , 3 , 4 , 6 }.

a = b | c ;
a = b + c ;
a |= b ;
a += b ;

& Intersection; { 1 , 2 , 3 } & { 2 , 4 , 6 } = { 2 }.

a = b & c ;
a &= b ;

- Relative complement; { 1 , 2 , 3 } - { 2 , 4 , 6 } = { 1 , 3 }.

a = b - c ;
a -= b ;

== Equality.

if ( a == b ) { ... }

!= Inequality.

if ( a != b ) { ... }

<= Subset.

if ( a <= b ) { ... }

< Subset but not equal.

if ( a < b ) { ... }

>= Superset.

if ( a >= b ) { ... }

> Superset but not equal.

if ( a > b ) { ... }

The following public methods and properties are also available

Add ( params object[] Items ) attempts to add the items to the Set. In some cases, this is more efficient than using the Union operator.

s.Add ( 1 ) ;
s.Add ( 1 , 2 ... ) ;
s.Add ( somearrayofints ) ;

Remove ( params object[] Items ) attempts to remove the items from the Set. In some cases, this is more efficient than using the relative complement operator.

s.Remove ( 1 ) ;
s.Remove ( 1 , 2 ... ) ;
s.Remove ( somearrayofints ) ;

Contains ( params object[] Items ) returns true if the Set contains the item(s), otherwise false. In some cases, this is more efficient than using the subset operator.

if ( s.Contains ( 1 ) ) { ... }
if ( s.Contains ( 1 , 2 ... ) ) { ... }
if ( s.Contains ( somearrayofints ) ) { ... }

Clear() removes all elements from the Set.

s.Clear() ;

Cardinality is the number of elements in the Set.

if ( s.Cardinality > 0 ) { ... }

EqualityComparer gets/sets the EqualityComparer of the underlying System.Collections.Generic.Dictionary.

Set<string> s = new Set<string> ( "abc" , "ABC" ) ;
System.Console.WriteLine ( s.EqualityComparer.ToString() ) ;
System.Console.WriteLine ( s.ToString() ) ;
s.EqualityComparer = System.StringComparer.CurrentCultureIgnoreCase ;
System.Console.WriteLine ( s.EqualityComparer.ToString() ) ;
System.Console.WriteLine ( s.ToString() ) ;

Yields:

System.Collections.Generic.GenericEqualityComparer`1[System.String]
{ abc , ABC }
System.CultureAwareComparer
{ abc }

ToString() traverses the Set performing ToString() on each element and concatenating the resultant strings together in proper Set format: { element1 , element2... }.

System.Console.Write ( s.ToString() ) ;

ToString ( SortMode SortMode , params object[] FormatInfo ) traverses the Set performing ToString ( FormatInfo ) on each element and concatenating the resultant strings together in proper Set format: { element1 , element2... }.

Set<int> s = new Set<int> ( 20 , 3 , 100 ) ;

System.Console.WriteLine ( s.ToString ( SortMode.None   ) ) ;
System.Console.WriteLine ( s.ToString ( SortMode.Native ) ) ;
System.Console.WriteLine ( s.ToString ( SortMode.String ) ) ;
System.Console.WriteLine ( s.ToString ( SortMode.None   , "000" ) ) ;
System.Console.WriteLine ( s.ToString ( SortMode.Native , "000" ) ) ;
System.Console.WriteLine ( s.ToString ( SortMode.String , "000" ) ) ;

Yields:

{ 20 , 3 , 100 }
{ 3 , 20 , 100 }
{ 100 , 20 , 3 }
{ 020 , 003 , 100 }
{ 003 , 020 , 100 }
{ 003 , 020 , 100 }

Interfaces

IEnumerable GetEnumerator returns the GetEnumerator of the underlying System.Collections.Generic.Dictionary's Keys property.

foreach ( int i in s ) { ... }

History

  • First submitted - 2006-11-14.
  • Updated 2006-11-15.
    • Added the ability to specify the EqualityComparer by using a Dictionary rather than a List.
    • Added the ability to specify formatting information to the ToString().

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PIEBALDconsult

Software Developer (Senior)

United States United States

Member

BSCS 1992 Wentworth Institute of Technology
 
Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.
 
OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB
 
---------------
 
"Typing is no substitute for thinking." -- R.W. Hamming
 
"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup
 
ZagNut’s Law: Arrogance is inversely proportional to ability.
 
"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon
 
"linq'ish" sounds like "inept" in German -- Andreas Gieriet
 

"Things would be different if I ran the zoo." -- Dr. Seuss
 
"Wrong is evil, and it must be defeated." – Jeff Ello
 
"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw
 

"Omit needless local variables." -- Strunk... had he taught programming
 
"DON'T BE LIBERAL IN WHAT YOU ACCEPT!"
 
"Software Engineers don't have Trophy Wives; they have Presentation Layers."
 
"We learn more from our mistakes than we do from getting it right the first time."
 
"I'm an old dog and I like old tricks."
 
"Sometimes the envelope pushes back and sometimes you get a really nasty paper cut."
 
"A method shall have one and only one return statement."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."
 
"Today's heresy is tomorrow's dogma."
or
"Today's dogma is yesterday's heresy."
 
"The registry is evil."
 
"Every tool is a hammer."

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralUnit Testing Pinmemberbrunzefb4:47 10 Feb '09  
GeneralRe: Unit Testing PinmemberPIEBALDconsult4:57 10 Feb '09  
Generalexception when comparing to null Pinmemberdeerchao21:47 3 Nov '07  
GeneralRe: exception when comparing to null PinmemberPIEBALDconsult4:27 4 Nov '07  
GeneralRe: exception when comparing to null Pinmemberdeerchao4:55 4 Nov '07  
GeneralRe: exception when comparing to null PinmemberPIEBALDconsult6:21 4 Nov '07  
GeneralRe: exception when comparing to null PinmemberPIEBALDconsult7:24 4 Nov '07  
GeneralRe: exception when comparing to null PinmemberPIEBALDconsult8:33 4 Nov '07  
GeneralRe: exception when comparing to null Pinmemberdeerchao14:05 4 Nov '07  
GeneralStopped Reading... PinPopularmemberDrell Hearthbake3:44 14 Aug '07  
GeneralRe: Stopped Reading... PinmemberPIEBALDconsult13:53 14 Aug '07  
GeneralRe: Stopped Reading... PinmemberJohnnyLocust6:22 29 Aug '07  
Don't be such a drama queen Drell.
QuestionOrdered Set PinmemberAstrodata1:59 18 Apr '07  
AnswerRe: Ordered Set PinmemberPIEBALDconsult3:58 15 Aug '07  
GeneralRe: Ordered Set PinmemberAstrodata22:00 15 Aug '07  
GeneralMuch appreciated! Pinmember2Scott211:12 14 Apr '07  
GeneralRe: Much appreciated! PinmemberPIEBALDconsult11:26 14 Apr '07  
GeneralNice contribution PinmemberPatB_Qc5:22 6 Dec '06  
GeneralRe: Nice contribution PinmemberPIEBALDconsult3:22 7 Dec '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 20 Nov 2006
Article Copyright 2006 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid