简体   繁体   中英

C# dictionary vs list usage

I had two questions. I was wondering if there is an easy class in the C# library that stores pairs of values instead of just one, so that I can store a class and an integer in the same node of the list. I think the easiest way is to just make a container class, but as this is extra work each time. I wanted to know whether I should be doing so or not. I know that in later versions of .NET ( i am using 3.5) that there are tuples that I can store, but that's not available to me.

I guess the bigger question is what are the memory disadvantages of using a dictionary to store the integer class map even though I don't need to access in O(1) and could afford to just search the list? What is the minimum size of the hash table? should i just make the wrapper class I need?

If you need to store an unordered list of {integer, value} , then I would suggest making the wrapper class. If you need a data structure in which you can look up integer to get value (or, look up value to get integer ), then I would suggest a dictionary.

The decision of List<Tuple<T1, T2>> (or List<KeyValuePair<T1, T2>> ) vs Dictionary<T1, T2> is largely going to come down to what you want to do with it.

If you're going to be storing information and then iterating over it, without needing to do frequent lookups based on a particular key value, then a List is probably what you want. Depending on how you're going to use it, a LinkedList might be even better - slightly higher memory overheads, faster content manipulation (add/remove) operations.

On the other hand, if you're going to be primarily using the first value as a key to do frequent lookups, then a Dictionary is designed specifically for this purpose. Key value searching and comparison is significantly improved, so if you do much with the keys and your list is big a Dictionary will give you a big speed boost.

Data size is important to the decision. If you're talking about a couple hundred items or less, a List is probably fine. Above that point the lookup times will probably impact more significantly on execution time, so Dictionary might be more worth it.

There are no hard and fast rules. Every use case is different, so you'll have to balance your requirements against the overheads.

您可以使用KeyValuePair列表: http//msdn.microsoft.com/en-us/library/5tbh8a42.aspx

You can use either KeyValuePair or Tuple

For Tuple, you can read the following useful post: What requirement was the tuple designed to solve?

您可以使用Tuple<T,T1>KeyValuePair<T, T1> - 或者匿名类型,例如

var list = something.Select(x => new { Key = x.Something, Value = x.Value });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM