I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages?
To create a tuple in Python, use the parentheses ( ), separated by commas. The parentheses are optional. A tuple can have many elements with different data types like integer, float, list, string, etc. To create a set in Python, use the parentheses { }, separated by commas.
Tuple — mutable elements Although tuples are immutable, they can contain mutable elements such as lists or sets.
Tuples has a sequence of elements of different data types. It was introduced to return an instance of the Tuple<T> with no need to specify the type of each element separately.
You can create 2-tuple using Tuple<T1, T2>(T1, T2) constructor. It initializes a new instance of the Tuple<T1,T2> class. But when you create a tuple using this constructor then you have to specify the type of the element stored in the tuple.
.NET 3.5 has HashSet.
.NET 4.0 will have a Tuple class. As noted in the article, earlier version of .NET do contain KeyValuePair< TKey, TValue > which is similar to a Tuple< T1, T2 >, with the main difference being that KeyValuePair requires that TKey is unique.
For Sets, HashSets (a .NET 3.5 feature) do the trick quite well.
A partial answer, for tuples:
Neither of these approaches are as convenient as with Python; the main handicap comes from the fact that C# is statically typed. However the C# 4.0 Tuple class has factory-like static methods which make the creation of tuples easier (up to 8-tuple, i.e. tuples with 8 members). For example one can have
var customer1 = Tuple.Create("John", "Smith", 14, 5.33, "202-123-444");
Using anonymous type can be done as follow. The main drawback of this approach is that one needs to explicitly name the elements of the "tuple" (although this naming can be implicitly "projected" if the values used for initialization are "projected" from another object.
customer1 = new Customer { Name = "John", Surname = "Smith", NumberOfVisits = 14, CurrentBalance = 5.33, PhoneNr = "202-123-444" };
If you're working with a .NET Framework earlier than already mentioned, Wintellect Power Collections might prove of some interest - it has Pair
and Triple
for 2- and 3-tuples, and collections such as Set
, Bag
, and Ordered
flavours of both.
Of course, there's nothing stopping you from implementing 4.0's Tuple
yourself.
(By the way, there's nothing particularly 'dynamic' about data structures like these in and of themselves)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With