Dictionary or List

I have strings associated with some double value. I need to be able to sort them easily by value and easily get strings as a kind of list. Maybe 100k + of these pairs.

So my question is, should I use a dictionary with strings as keys and double as values ​​or a KeyValuePairs list with the same keys and values?

In the case of a dictionary, it is easy to get the keys as a list through

dict.Keys.toList()

and in case of a list it’s easy to sort by value through

list.Sort(delegate(KeyValuePair x, KeyValuePair y) { return y.Value.CompareTo(x.Value); }) .

I did not find a way to do both. What do you recommend?

+4
source share
5 answers

here is 1 way to select all rows in the KeyValue list with a value of 1 or select all rows from a key pair

 List<string> onestrings = list.Where(a=>a.Value == 1).Select(a => a.Key).ToList(); List<string> allstrings = list.Select(a => a.Key).ToList(); 
+1
source

I would recommend SortedList<double, string> . This is similar to what you want:

  • Automatically sorted by double values ​​( Keys property)
  • Lines are available in order through the Values property.

This will only work if your double values ​​are unique. Otherwise, you can wrap SortedList<double, List<string>> in your own collection, for example:

 class DoubleStringList { SortedList<double, List<string>> _strings = new SortedList<double, List<string>>(); public void Add(string str, double value) { List<string> list; if (!_strings.TryGetValue(value, out list)) { _strings[value] = list = new List<string>(); } list.Add(str); } public IEnumerable<KeyValuePair<double, string>> GetEntries() { var entries = from entry in _strings from str in entry.Value select new KeyValuePair<double, string>(entry.Key, str); return entries; } } 
+3
source

One of the main considerations is whether your values ​​are unique. If this is not the case, the dictionary will not work, as this requires unique keys. It will also be harder to sort.

If you just use this to store pairs of values, and there are no uniqueness restrictions, I would personally use List<Tuple<double,string>> .

+1
source

I assume that you have several lines for a given double value.

You can still do it differently: Dictionary<double, list<string>>

So you would take a double value as a key, and when you get a string with the same double value, you add it to the list.

Thus, you get the dictionary search speed, and if necessary, you can make some keys.

0
source

How about a search ?

 Dictionary<string,double> dic = new Dictionary<string,double>(); ILookup<double,string> lookup = dic.ToLookup(kvp => kvp.Value, kvp => kvp.Key); 
0
source

Source: https://habr.com/ru/post/1338898/


All Articles