It is possible to override the TryGetIndex method of a dynamic object to access the dynamic object properties by index however I am dealing with an Expandoobject (of the System.dynamic namespace) which you can't inherit from. Is there a way around this? Thanks
ExpandoObject is nothing but a fancy IDictionary which leverages the DLR.
There is no way you can access a IDictionary<TKey,TValue> via index. You may find ElementAt method of linq useful, but it is not. There is no ordering in dictionary, You can read more about hashtable datastructure(Dictionary is also a hashtable).
For accessing dictionary via index you may use OrderedDictionary. One disadvantage is that is is not generic.
Know more about issues when accessing elements via index from a Dictionary
Related
What would be the best data type for storing non-unique pairs of objects? I cannot use Dictionary because the key has to be unique. I could create an object with the two data types as properties and store them in a list, but that wouldn't be flexible enough to accommodate the different data type pairs. Something almost like Dictionary but non-unique. A build-in solution from .NET would be even better.
I think a List<Tuple<T1,T2>> would work best here.
List<T>
Tuple<T1,T2>
You could use List<KeyValuePair<T1,T2>>. Dictionary class uses KeyValuePair too.
can any body have idea for create dynamic class at run time.i have one dictionary<string,object> which is contains datatable's all columns with it's datatype my plan is to create a dynamic class base on dictionary. means datatable's column name is property of class. after create list<dynamic class> and bind to grid
it's grate help if you have code for it
meta-programming on Silverlight is fairly limited, but TypeBuilder is probably what you are looking for. An easier option, though, is to use ExpandoObject and dynamic, but frankly: you might as well just use the dictionary. I'm not sure I'd bother going to the trouble of meta-programming for this.
If you do go that route, you can get a new empty list via:
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(newType));
I have a class (SomeClass) which contains a property Name of string type. And I need to store an array of that class and find its items by their names. For this purpose there are two types of collections: KeyedCollection and Dictionary. My question is: What difference between them and in such case It is better to use KeyedCollection and Dictionary? Thanks for any help in explanation.
None of the previous comments address the most important difference between the two:
KeyedCollection keeps your items in the order in which they are added (the first item added is at index 0 and the last added is at the last index). Dictionary does not (or at least it is never guaranteed to do so).
This extra benefit of KeyedCollection does have a small performance cost. Under the covers, you pay the cost of maintaining both a Dictionary and a List.
Here is good explanation about differences between Dictionary and KeyedCollection: http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx
Main points are:
KeyedCollection is abstract, so you can't use it directly.
KeyedCollection is useful for cases, when key is in entity itself, then you can encapsulate key retrieval within collection implementation.
There are generic implementations for KeyedCollection (not in the framework though), which allow you to paste key retrieval delegate in collection constructor, so you don't have to repeat it each time you add item.
Update: as long as original link to article was removed, adding link to web archive: https://web.archive.org/web/20200228045828/http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx
A KeyedCollection allows mutable keys and ways to manage change in key. Dictionary does not allow changes to key. Secondly, if you have a collection which needs lookup, the logic to extract key from entity remains in one place - whereas maintaining dictionary will need to put key extraction logic at each place where items are added/removed from dictionary.
By default a KeyedCollection creates a Dictionary under the covers.
If the Key also has meaning as part of the Value and also defines uniqueness then that is the purpose of a KeyedCollection.
If you want to modify the dictionary backing then use this ctor:
protected KeyedCollection(
IEqualityComparer<TKey> comparer,
int dictionaryCreationThreshold)
A KeyedCollection should be used when the key is on the item itself.
By default, KeyedCollection is a Collection<TItem> wrapper around a dictionary. When you use small collections and/or you prefer retrieving items directly, the KeyedCollection provides a constructor that takes a dictionaryCreationThreshold parameter, that indicates at what collection count to switch to Dictionary.
Another aspect in KeyedCollection is that you can choose to switch the key property (as long as their types match). This can be good for double keyed items etc.
Performancewise, I don't think wrapping a dictionary has much overhead except if you generate a bunch of KeyedCollection instances, or if you use really large collections (there are some internal null checks to determine if there is a dictionary).
One thing I'd hope to see in KeyedCollection is unabstracting it, but you can make a generic concrete type just as easy.
You can't use KeyedCollection because it's abstract: http://msdn.microsoft.com/en-us/library/ms132438.aspx. This means you can't create an object of it.
I need to sort the data in a Hashtable by a property of the object added to the collection. how to do that? my project uses .NET 2.0, so I can't use any features that do not work by default in .NET 2.0 runtime (I may be able to use some of the C# 3.0 features that will work on .NET 2.0 without adding references to any new dlls). all the objects added to hashtable are of the same type. If I use SortedList and pass Hashtable to it (through constructor), then it sorts only by keys, is there a way to pass custom sorting logic to it?
if you are bound to .NET 2.0 you can use IComparer.
http://codebetter.com/davidhayden/2005/02/27/implementing-icomparable-for-sorting-custom-objects/
a Hashtable is definetly the wrong datastructure if you want to sort something.
#Snoopy said IComparer, that is indeed what you need. Take a look at SortedDictionary.
Take a look at the drawbacks of a hash table. Then look at the advantages and determine if you are using the right data structure. If you very rarely sort, then you may be using the right data structure. In this case, sorting will require you enumerate the values and put them into a list. If sort if frequent, consider moving to a different data structure, like a search tree. If you rarely do lookups/searches, I would consider using an ordinary list.
One option, if you want to stick to creating a sorted list from the contents of a Hashtable, is to write a subclass of IComparer, overload the Compare method as needed, and create a Sorted list using:
SortedList s = new SortedList( new MyIComparer() );
Then add the elements of your Hashtable to the list accordingly.
I'm iterating through a List<> to find a matching element. The problem is that object has only 2 significant values, Name and Link (both strings), but has some other values which I don't want to compare.
I'm thinking about using something like HashSet (which is exactly what I'm searching for -- fast) from .NET 3.5 but target framework has to be 2.0. There is something called Power Collections here: http://powercollections.codeplex.com/, should I use that?
But maybe there is other way? If not, can you suggest me a suitable custom collection?
In .NET 2.0 instead of a HashSet<T> you can use a Dictionary<K, V>.
Dictionary uses the hash code to perform key lookups so it has similar performace to the HashSet. There are at least two approaches:
Create a custom class or struct containing the Name and Link and use that as the key in the dictionary, and put the object as the value.
Store the entire object as the key and provide a custom equality comparer that only looks at the Name and Link member, and set the value to null.
The second method is very similar to how you would use a HashSet if it were available.
How about this:
Custom class/collection wich will held List of objects and two dictionaries, one for the name and one for the link. Both of them will have a int value wich will be the index of object. I think that in that case I will only need to check if there is such int value of name dictionary that equals link dictionary int.
Is this a good approach?