Generic collections
-
KeyValuePair i_item = d.ElementAt(2); // if d is a Dictionary it is not possible
may be I was not clear I can't get item from index value. For example I need the second element How can I ask the Dictionary the second element? The dictionary is an unsorted collection
An unsorted collection is what you're looking for if you want to prevent the order in which the items were added. And I don't know what error you're getting when calling
KeyValuePair i_item = d.ElementAt(2);
as this works just fine for me with a dictionary
-
An unsorted collection is what you're looking for if you want to prevent the order in which the items were added. And I don't know what error you're getting when calling
KeyValuePair i_item = d.ElementAt(2);
as this works just fine for me with a dictionary
thanks you are right sorry. Basically I need to find the index from the key and viceversa. How can I find the index related to the key "3", from the dictionary. It should be 2
-
thanks you are right sorry. Basically I need to find the index from the key and viceversa. How can I find the index related to the key "3", from the dictionary. It should be 2
Why do you need to be able to get the index of a KeyValuePair if you already got the key? :confused: Maybe take a look at the hint from Keith. Note: As I just saw after a bit of researching, the Dictionary uses some hashing of the keys to create some order which means it does not necessarily return the items in the order in which they were added Source: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^]
Quote:
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
-
Ordered Dictionary[^] has access via the index and the key. Looks promising.
PB 369,783 wrote:
I just find him very unlikeable, and I think the way he looks like a prettier version of his Mum is very disturbing.[^]
But its not Generic :laugh: Well one could create a Generic wrapper for it ;)
-
But its not Generic :laugh: Well one could create a Generic wrapper for it ;)
:doh: I'll get me coat.
PB 369,783 wrote:
I just find him very unlikeable, and I think the way he looks like a prettier version of his Mum is very disturbing.[^]
-
I need to use a generic collection of keyvalue pair. I need thr folloeing: 1) should be generic because my values are a customized class 2) iterating should keep the order in which I added Items 3) I should be able to find the index of the element 4) I need access via Key A dictionary is ok for 1,2,4 but not for 3 SortedList and SortedDictionary are ok for 1, 3, 4 but not for 2. If I create a
List
it is ok for 1,2,3 but not for 4 ( I mean not directly)
//Dictionary d = new Dictionary();
SortedList d = new SortedList();
d.Add("z", 1);
d.Add("a", 2);
d.Add("c", 3);
d.Add("b", 4);foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); }
// output: a 2 b 4 c 3 z 1
// but i need to preserve the order in whicth I added.
// I need output: z 1 a 2 c 3 b 4
// using Dictionary I preserve the order but how can select item using an index?KeyValuePair i_item = d.ElementAt(2); // if d is a Dictionary it is not possible
Any suggestion? Thanks for your time
This article might help: OrderedDictionary<T>: A generic implementation of IOrderedDictionary[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
I need to use a generic collection of keyvalue pair. I need thr folloeing: 1) should be generic because my values are a customized class 2) iterating should keep the order in which I added Items 3) I should be able to find the index of the element 4) I need access via Key A dictionary is ok for 1,2,4 but not for 3 SortedList and SortedDictionary are ok for 1, 3, 4 but not for 2. If I create a
List
it is ok for 1,2,3 but not for 4 ( I mean not directly)
//Dictionary d = new Dictionary();
SortedList d = new SortedList();
d.Add("z", 1);
d.Add("a", 2);
d.Add("c", 3);
d.Add("b", 4);foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); }
// output: a 2 b 4 c 3 z 1
// but i need to preserve the order in whicth I added.
// I need output: z 1 a 2 c 3 b 4
// using Dictionary I preserve the order but how can select item using an index?KeyValuePair i_item = d.ElementAt(2); // if d is a Dictionary it is not possible
Any suggestion? Thanks for your time
I really like (and upvoted) your question; it was fun to see what I could implement quickly, and I'm going to post the code here before I read the other responses on the thread, since I feel I can learn something from knowing whether or not the code I post actually meets your requirements, and, possibly, learning from other people's responses. I wonder if I have not just duplicated the functionality of a Dictionary<K, V> ? Also, I suspect Linq queries could be used in some way, efficiently here, rather than, as I did, creating two Lists in the class (memory cost ?). Disclaimer: I've tested only with KeyValuePair<string, double> since that's what you used. Testing with instances of a custom class as K, or V: that's on my list :) Here's the revised class:
public class IndexedKVPList<K, V> : List<KeyValuePair<K, V>>
{
private readonly List<K> keyList = new List<K>();
private readonly List<V> valueList = new List<V>();// modified to use 'new new public void Add(KeyValuePair<K, V> newKVP) { keyList.Add(newKVP.Key); valueList.Add(newKVP.Value); base.Add(newKVP); } // new function to Remove KeyValue pair new public void Remove(KeyValuePair<K, V> killKVP) { if(! this.Contains(killKVP)) throw new Exception("error in Remove in IndexedKVPPair"); keyList.Remove(killKVP.Key); valueList.Remove(killKVP.Value); base.Remove(killKVP); } public KeyValuePair<K, V> GetKVPByValue(V theValue) { return this\[valueList.IndexOf(theValue)\]; } public K GetKeyByValue(V theValue) { return this\[valueList.IndexOf(theValue)\].Key; } // new function to get the index by KeyValue pair public int GetIndexByKVP(KeyValuePair<K, V> theKVPPair) { return this.IndexOf(theKVPPair); } // new function to get the index by Value // what happens if there are multiple identical values ? public int GetIndexByValue(V theValue) { return (valueList.IndexOf(theValue)); } public KeyValuePair<K, V> GetKVPByKey(K theKey) { return this\[keyList.IndexOf(theKey)\]; } public V GetValueByKey(K theKey) { return this\[keyList.IndexOf(theKey)\].Value; } // new function to get the index by Key public int GetIndexByKey(K theKey) { re
-
I need to use a generic collection of keyvalue pair. I need thr folloeing: 1) should be generic because my values are a customized class 2) iterating should keep the order in which I added Items 3) I should be able to find the index of the element 4) I need access via Key A dictionary is ok for 1,2,4 but not for 3 SortedList and SortedDictionary are ok for 1, 3, 4 but not for 2. If I create a
List
it is ok for 1,2,3 but not for 4 ( I mean not directly)
//Dictionary d = new Dictionary();
SortedList d = new SortedList();
d.Add("z", 1);
d.Add("a", 2);
d.Add("c", 3);
d.Add("b", 4);foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); }
// output: a 2 b 4 c 3 z 1
// but i need to preserve the order in whicth I added.
// I need output: z 1 a 2 c 3 b 4
// using Dictionary I preserve the order but how can select item using an index?KeyValuePair i_item = d.ElementAt(2); // if d is a Dictionary it is not possible
Any suggestion? Thanks for your time
Often when you have a problem that looks like "I need a data structure that has the properties of A and of B" where A and B are some data structure, there's an obvious way to just combine A and B and wrap them a little thing that keeps them synchronized. Such as here, it looks like a List and like a Dictionary.. what can you do? Well you can make a List<Tvalue> and a Dictionary<Tkey, int> and let the dictionary map keys to indexes in the list. If you also want removal, you can use a linked list instead of a list, and let the dictionary map keys to nodes in the linked list.
-
I need to use a generic collection of keyvalue pair. I need thr folloeing: 1) should be generic because my values are a customized class 2) iterating should keep the order in which I added Items 3) I should be able to find the index of the element 4) I need access via Key A dictionary is ok for 1,2,4 but not for 3 SortedList and SortedDictionary are ok for 1, 3, 4 but not for 2. If I create a
List
it is ok for 1,2,3 but not for 4 ( I mean not directly)
//Dictionary d = new Dictionary();
SortedList d = new SortedList();
d.Add("z", 1);
d.Add("a", 2);
d.Add("c", 3);
d.Add("b", 4);foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); }
// output: a 2 b 4 c 3 z 1
// but i need to preserve the order in whicth I added.
// I need output: z 1 a 2 c 3 b 4
// using Dictionary I preserve the order but how can select item using an index?KeyValuePair i_item = d.ElementAt(2); // if d is a Dictionary it is not possible
Any suggestion? Thanks for your time
use Dictionary
-
Often when you have a problem that looks like "I need a data structure that has the properties of A and of B" where A and B are some data structure, there's an obvious way to just combine A and B and wrap them a little thing that keeps them synchronized. Such as here, it looks like a List and like a Dictionary.. what can you do? Well you can make a List<Tvalue> and a Dictionary<Tkey, int> and let the dictionary map keys to indexes in the list. If you also want removal, you can use a linked list instead of a list, and let the dictionary map keys to nodes in the linked list.
I did the same as a workaround solution... thanks a lot
-
I really like (and upvoted) your question; it was fun to see what I could implement quickly, and I'm going to post the code here before I read the other responses on the thread, since I feel I can learn something from knowing whether or not the code I post actually meets your requirements, and, possibly, learning from other people's responses. I wonder if I have not just duplicated the functionality of a Dictionary<K, V> ? Also, I suspect Linq queries could be used in some way, efficiently here, rather than, as I did, creating two Lists in the class (memory cost ?). Disclaimer: I've tested only with KeyValuePair<string, double> since that's what you used. Testing with instances of a custom class as K, or V: that's on my list :) Here's the revised class:
public class IndexedKVPList<K, V> : List<KeyValuePair<K, V>>
{
private readonly List<K> keyList = new List<K>();
private readonly List<V> valueList = new List<V>();// modified to use 'new new public void Add(KeyValuePair<K, V> newKVP) { keyList.Add(newKVP.Key); valueList.Add(newKVP.Value); base.Add(newKVP); } // new function to Remove KeyValue pair new public void Remove(KeyValuePair<K, V> killKVP) { if(! this.Contains(killKVP)) throw new Exception("error in Remove in IndexedKVPPair"); keyList.Remove(killKVP.Key); valueList.Remove(killKVP.Value); base.Remove(killKVP); } public KeyValuePair<K, V> GetKVPByValue(V theValue) { return this\[valueList.IndexOf(theValue)\]; } public K GetKeyByValue(V theValue) { return this\[valueList.IndexOf(theValue)\].Key; } // new function to get the index by KeyValue pair public int GetIndexByKVP(KeyValuePair<K, V> theKVPPair) { return this.IndexOf(theKVPPair); } // new function to get the index by Value // what happens if there are multiple identical values ? public int GetIndexByValue(V theValue) { return (valueList.IndexOf(theValue)); } public KeyValuePair<K, V> GetKVPByKey(K theKey) { return this\[keyList.IndexOf(theKey)\]; } public V GetValueByKey(K theKey) { return this\[keyList.IndexOf(theKey)\].Value; } // new function to get the index by Key public int GetIndexByKey(K theKey) { re
Thanks a lot, I did a workaround using a syncronized List.. Then I found the following solution
Dictionary d = new Dictionary();
d.Add("z", 1); d.Add("a", 2); d.Add("c", 3); d.Add("b", 4); foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); } KeyValuePair i\_item = d.ElementAt(2); int myIndex = Array.IndexOf(d.Keys.ToArray(), "a");
-
Often when you have a problem that looks like "I need a data structure that has the properties of A and of B" where A and B are some data structure, there's an obvious way to just combine A and B and wrap them a little thing that keeps them synchronized. Such as here, it looks like a List and like a Dictionary.. what can you do? Well you can make a List<Tvalue> and a Dictionary<Tkey, int> and let the dictionary map keys to indexes in the list. If you also want removal, you can use a linked list instead of a list, and let the dictionary map keys to nodes in the linked list.
Hi Harold, Upvoted, as usual: why is it that when I read your comments, I often feel like I am listening to Yoda trying to tell me something through metaphor that's just beyond my ability to grasp ? :) yours, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
-
Thanks a lot, I did a workaround using a syncronized List.. Then I found the following solution
Dictionary d = new Dictionary();
d.Add("z", 1); d.Add("a", 2); d.Add("c", 3); d.Add("b", 4); foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); } KeyValuePair i\_item = d.ElementAt(2); int myIndex = Array.IndexOf(d.Keys.ToArray(), "a");
It may be a little faster to get the index using:
private int theIndex;
//
theIndex = dictionaryStringInt.Keys.ToList<string>().IndexOf("KeyString");However, note that in using both 'ElementAt, and 'ToArray ... or 'ToList ... you are using Linq functions that are, internally, going to do an enumeration. If the entries in the dictionary are not being removed, moved around, etc., then you could create a List once from the Keys collection, however, I doubt that's the case you want here. I will add some extra functions that return an index to my first answer above, with the hope some of our members here who have more formal computer science training (than I do) will comment on the relative cost / lookup-times, of the example I've given. good luck, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
-
Thanks a lot, I did a workaround using a syncronized List.. Then I found the following solution
Dictionary d = new Dictionary();
d.Add("z", 1); d.Add("a", 2); d.Add("c", 3); d.Add("b", 4); foreach (KeyValuePair k in d) { Console.WriteLine(k.Key + " " + k.Value); } KeyValuePair i\_item = d.ElementAt(2); int myIndex = Array.IndexOf(d.Keys.ToArray(), "a");
That doesn't work. Or rather, it may work - accidentally. But see http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx[^]:
The order of the keys in the Dictionary.KeyCollection is unspecified
It is not (necessarily) in the order that you added the items. It often works. But it isn't guaranteed to. edit: it turns out that, in the current implementation (which may change!) it will indeed work as long as you never delete anything. That's just an implementation detail, it would be foolish to rely on it. It could change in any update. Also, of course, you're doing a linear search through a list. That is not ideal.
-
It may be a little faster to get the index using:
private int theIndex;
//
theIndex = dictionaryStringInt.Keys.ToList<string>().IndexOf("KeyString");However, note that in using both 'ElementAt, and 'ToArray ... or 'ToList ... you are using Linq functions that are, internally, going to do an enumeration. If the entries in the dictionary are not being removed, moved around, etc., then you could create a List once from the Keys collection, however, I doubt that's the case you want here. I will add some extra functions that return an index to my first answer above, with the hope some of our members here who have more formal computer science training (than I do) will comment on the relative cost / lookup-times, of the example I've given. good luck, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
thanks very useful
-
Hi Harold, Upvoted, as usual: why is it that when I read your comments, I often feel like I am listening to Yoda trying to tell me something through metaphor that's just beyond my ability to grasp ? :) yours, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
:)
-
That doesn't work. Or rather, it may work - accidentally. But see http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx[^]:
The order of the keys in the Dictionary.KeyCollection is unspecified
It is not (necessarily) in the order that you added the items. It often works. But it isn't guaranteed to. edit: it turns out that, in the current implementation (which may change!) it will indeed work as long as you never delete anything. That's just an implementation detail, it would be foolish to rely on it. It could change in any update. Also, of course, you're doing a linear search through a list. That is not ideal.
oky thank
-
That doesn't work. Or rather, it may work - accidentally. But see http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx[^]:
The order of the keys in the Dictionary.KeyCollection is unspecified
It is not (necessarily) in the order that you added the items. It often works. But it isn't guaranteed to. edit: it turns out that, in the current implementation (which may change!) it will indeed work as long as you never delete anything. That's just an implementation detail, it would be foolish to rely on it. It could change in any update. Also, of course, you're doing a linear search through a list. That is not ideal.
harold aptroot wrote:
you're doing a linear search through a list.
Hi Harold, I am curious: do you know for a fact that using Linq 'ElementAt, or using the (not Linq) 'IndexOf on an Array, or List, internally performs a linear search ? In the case of 'ElementAt on a Dictionary, I am assuming there's some cost of some kind of internal conversion since Dictionary doesn't inherently support "sequential" indexing by integer. thanks, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
-
harold aptroot wrote:
you're doing a linear search through a list.
Hi Harold, I am curious: do you know for a fact that using Linq 'ElementAt, or using the (not Linq) 'IndexOf on an Array, or List, internally performs a linear search ? In the case of 'ElementAt on a Dictionary, I am assuming there's some cost of some kind of internal conversion since Dictionary doesn't inherently support "sequential" indexing by integer. thanks, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal
The IndexOf of a List uses the IndexOf of Array, and that ones's a linear search (I checked it just be sure, but really there's no other choice anyway). What ElementAt does depends on the thing you're applying it to, it will use IList<T>'s indexer if that interface is implemented (Dictionary does not implement it, so ElementAt would scan through the enumerator). So in conclusion, that code was pretty inefficient.
-
The IndexOf of a List uses the IndexOf of Array, and that ones's a linear search (I checked it just be sure, but really there's no other choice anyway). What ElementAt does depends on the thing you're applying it to, it will use IList<T>'s indexer if that interface is implemented (Dictionary does not implement it, so ElementAt would scan through the enumerator). So in conclusion, that code was pretty inefficient.
Thanks for your reply, Harold, that is very interesting to know. It makes me wonder: if you were dealing with a really big generic List, or a huge Dictionary, if you could implement a much more efficient solution than the current operators, and, if so, why MS has not done that. I would have thought that Linq operators, particularly, were highly optimized with the latest algorithms: reminds me I should never assume anything about software tools. yours, Bill
~ “This isn't right; this isn't even wrong." Wolfgang Pauli, commenting on a physics paper submitted for a journal