What is the difference between LINQ ToDictionary and ToLookup - c#

What is the difference between LINQ ToDictionary and ToLookup? They seem to do the same thing.

A dictionary is a 1:1 map (each key is mapped to a single value), and a dictionary is mutable (editable) after the fact.
A lookup is a 1:many map (multi-map; each key is mapped to an IEnumerable<> of the values with that key), and there is no mutate on the ILookup<,> interface.
As a side note, you can query a lookup (via the indexer) on a key that doesn't exist, and you'll get an empty sequence. Do the same with a dictionary and you'll get an exception.
So: how many records share each key?
An overly simplified way of looking at it is that a Lookup<TKey,TValue> is roughly comparable to a Dictionary<TKey,IEnumerable<TValue>>

ToDictionary is <TKey, TValue> while ToLookup<TKey, T1, T2, T3, ...> is is similar to IGrouping but enumeration stays in memory.

Related

Can anyone give an example of a generic type for dynamically growing chained hashtables?

What's the best way to implement a chained hashtable in C#? For example, the class would be declared like this:
DynamicHashtable<Tkey, Tvalue>
{
....methods
}
Where Tkey is the type of the key stored in the table, and TValue is the type of the values associated with the keys. Thus, a hashtable whose keys are strings and whose associated values are integers would be
DynamicHashtable<string, int>
You can use Hashtable class.
If you wish to see details of implementation Hashtable you can review Source Code here.

Why doesn't IGrouping inherit IEnumerable<KeyValuePair> like IDictionary?

IGrouping:
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>,
IEnumerable
IDictionary:
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>,
IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
So, IDictionary implements IEnumerable<KeyValuePair<TKey, TValue>> while IGrouping implements IEnumerable<TElement>. If the elements of IGrouping contain keys, why does the interface not also use KeyValuePair? It also seems like methods implemented in IDictionary that would be useful for IGrouping such as IDictionary.ContainsKey are unavailable in IGrouping, meaning any attempt to find a key on a group (in O(1) time) would look something like:
List<int> myList = new List<int>{ 1, 2, 3, 1};
var grp = myList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
if (grp.ContainsKey(someValue)){...}
Am I just using IGrouping wrong? What am I missing?
To find if a particular IGrouping<TKey, TValue> contains a particular TKey, just check its Key property directly. No need for a loop.
GroupBy doesn't return IGrouping, it returns IEnumerable<IGrouping<...>>. That is, IGrouping represents the results for one single key value, and you get multiple such results. It cannot return Dictionary<TKey, TValue>, as GroupBy preserves key order, and Dictionary doesn't. No other pre-existing collection type is appropriate here.
Since you don't care about key order, and also don't care about the individual values for each key (since they're identical), you can store your results in a dictionary yourself, like you're doing now. You're doing the right thing.
If you don't need the counts, you can also use a HashSet<int>.
If you end up needing the individual values, you can also use ToLookup.

Sorting IDictionary Generic

I need to know if there is any way of ordering an IDictionary without knowing what type it is exactly ...
For example, I have a method that received an object and within this I have a Dictionary object ... all I know is that it is a Dictionary
so I can do this:
public void MyMethod(PropertyInfo propriedadeParametro, object parameters){
IDictionary dictionary = ((IDictionary) propriedadeParametro.GetValue (parameters, null));
}
but need sort the items of this Dictionary by EnumPersonalizado regardless of what the other Type "something?" has
You can't sort a dictionary. A dictionary, by definition, doesn't have an "order" of the items within it. The items are stored in some mechanism that is beyond your control that is designed to make it as efficient as possible for adding, removing, and searching.
The best that you can do is take all of the items out of the dictionary, put them in some other sort of collection, and then sort that.
As to your particular case, it's not clear to us what the type of the key or the value in the dictionary is, and that would need to be known in order to be able to try to sort the data.
see this question.
Dictionaries by themselves don't have an index order. Consider inheriting from the KeyedCollection class instead. It's a merge of a dictionary and an ordinary list, and it's designed to use a member of your items as the key, and have an index order.
There are plenty of legitimate reasons to want to apply a partial ordering to dictionaries based on key, it isn't a fundamental quality that keys be unordered, only that a given key will yield a given value.
That being said, if you find yourself with a non-generic IDictionary, it can actually be quite troublesome to 'sort' by key without knowledge of the key type. In my specific scenario, I wanted a function which would transform an IDictionary into another IDictionary where the entries could be enumerated by the ordered keys.
IDictionary ToSortedDictionary(IDictionary dictionary) {
return new SortedList(dictionary);
}
This will construct a new dictionary instance, such that traversals (foreach) will visit the entries based on the sort order of the keys.
The oddly named SortedList can be found in System.Collections and orders keys using the ÌComparable interface.
IDictionary is IEnumerable, so you can try to do something like new ArrayList(dictionary).Sort(), but it will try to cast members to IComparable, or you can use a Sort overload which accepts an IComparer object.
Another way is to use a reflection - first you find actual Keys/Values types and then you create a call to generic OrderBy.

When SortedDictionary is enumerated does it return KeyValuePairs in expected order?

When I have SortedDictionary<TK, TV> in .NET and I want to enumerate it as ICollection<KeyValuePair<TK, TV>> does it enumerate in expected order?
That is KeyValuePair<TK, TV> with lowest key is returned as first, folloved by KeyValuePair<TK, TV> with second lowest key etc.?
Note: Only answer backed up by reference will be accepted.
From the Reference for GetEnumerator:
"The dictionary is maintained in a sorted order using an internal tree. Every new element is positioned at the correct sort position, and the tree is adjusted to maintain the sort order whenever an element is removed. While enumerating, the sort order is maintained."
Specifically: "While enumerating, the sort order is maintained."
Yes definitely, although you are going to find it very hard to find documentation that clarifies this precisely.
Although the documentation for each of the four GetEnumerator overloads on this type make vague statements about returning "an enumerator that iterates through a collection", it is obvious enough that they should produce equivalent (sorted by key) sequences; remember that a sorted-dictionary is meant to "represent a collection of key/value pairs that are sorted on the key." It would be highly unintuitive and confusing for users if a collection behaved completely differently (i.e. with a different enumeration order) between a foreach loop and a LINQ to Objects query, for example.
The best I can do is provide you with the implementations of the two GetEnumerator methods you appear to be interested in (as of .NET 4.0). They are identical - they return an instance of the nested Enumerator type, with the same arguments for its constructor. The only difference is the boxing of the struct-type in the second overload:
// Used when you do foreach(var kvp in dict) { ... }
public Enumerator<TKey, TValue> GetEnumerator()
{
return new Enumerator<TKey, TValue>
((SortedDictionary<TKey, TValue>) this, 1);
}
// Used when you do:
// foreach(var kvp in (ICollection<KeyValuePair<TKey, TValue>>)dict) { ... }
// or use LINQ to Objects on the collection.
IEnumerator<KeyValuePair<TKey, TValue>>
IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator<TKey, TValue>
((SortedDictionary<TKey, TValue>) this, 1);
}
In fact, the only GetEnumerator overload that has a slightly different implementation is the IDictionary.GetEnumerator method. This changes an argument to the constructor-call such that the resulting enumerator produces DictionaryEntry instances rather than KeyValuePair<,> instances. Of course, the enumeration order will still be the same as with the other overloads.
It depends on the default IComparer implementation of the key, assuming you are not passing one in:
SortedDictionary(Of TKey, TValue) requires a comparer implementation to perform key comparisons. You can specify an implementation of the IComparer(Of T) generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic comparer Comparer(Of T).Default is used. If type TKey implements the System.IComparable(Of T) generic interface, the default comparer uses that implementation.
Look at the Remarks section of the SortedDictionary<TKey, TValue> page.
So, if your key is a string, the string implementation of IComparable will be used, if an int32 the int32 implementation will be used.

ILookup interface vs IDictionary

How does the ILookup<key, value> interface differ from IDictionary<key, value>?
I don't understand what the ILookup interface is meant for.
ILookup entries can contain multiple items per key - each key is mapped to an IEnumerable<TElement>.
Also as hinted to in the comments an ILookup is immutable, while you can update values in an IDictionary (it exposes an Add() method and an indexer that allows getting and setting values).
In summary their use case is very different - you use a lookup when you need a 1:N map with values that are fixed and won't (and can't) change. A dictionary on the other hand offers a mutable 1:1 mapping of key value pairs, so it can be updated to add or remove values.
It is much more simpler than IDictionary. It is used by Linq. It only has Contains, Item and Count. IDictionary has Add, Remove, etc.
ILookUp => Group by key , Enumerable Collection
Single key value refers to enumerable collection where we can iterate through the value collection.
IDictionary => Group by distinct key , Single value

Categories

Resources