简体   繁体   English

c#中的列表<>和字典<>有什么区别

[英]what is the difference between list<> and dictionary<> in c#

I have a strange doubt regarding list and dictionary in c#我对 C# 中的列表和字典有一个奇怪的疑问

In a list we add items to list by using the following method在列表中,我们使用以下方法将项目添加到列表

using System.Collections.Generic;

class Program
{
    static void Main()
    {
       List<int> list = new List<int>();
       list.Add(2);
       list.Add(3);
       list.Add(5);
       list.Add(7);
    }
}

In a dictionary we add items like this ...在字典中,我们添加这样的项目......

using System;
using System.Collections.Generic;

class Program
{
   static void Main()
   {
      Dictionary<string, int> d = new Dictionary<string, int>();
      d.Add("cat", 2);
      d.Add("dog", 1);
      d.Add("llama", 0);
      d.Add("iguana", -1);
   }
}

I don't know exactly what is the difference, but in a dictionary we add items like a (key,value) pair and in a list we just add items without specifying any key ..我不知道到底有什么区别,但是在字典中我们添加了像 (key,value) 对这样的项目,而在列表中我们只添加了项目而不指定任何键..

Would anyone clarify this?有人会澄清这一点吗?

IDictionary is for key->value maps, ICollection is for sets of similar objects. IDictionary用于键-> 值映射, ICollection用于相似对象的集合。

ICollection is an interface for collections of similar objects: the controls on a form, the elements in a list, the attributes in an XML tag, and so on. ICollection是类似对象集合的接口:表单上的控件、列表中的元素、XML 标记中的属性等等。 As of .NET 2.0, there's a generic version, so you can refer to a collection of integers as ICollection<int> .从 .NET 2.0 开始,有一个通用版本,因此您可以将整数集合称为ICollection<int>

IDictionary is an interface for mapping one type of object or value to another. IDictionary 是用于将一种类型的对象或值映射到另一种类型的接口。 It works like a real dictionary, or a phone book: you have a "key" in mind like a person's name, and when you look it up, you get some information that's identified by that key, like an address or phone number.它就像一本真正的字典或电话簿:你有一个“钥匙”,比如一个人的名字,当你查找它时,你会得到一些由该钥匙识别的信息,比如地址或电话号码。 Each key can only be listed once, although two different keys are still allowed to have the same value.每个键只能列出一次,尽管仍然允许两个不同的键具有相同的值。 This is also generic in .NET 2.0, so a dictionary whose keys are strings and whose values are integers would be IDictionary<string,int> .这在 .NET 2.0 中也是通用的,因此键为字符串且值为整数的字典将是IDictionary<string,int>

A dictionary is actually a collection of key/value pairs: you can use an IDictionary<int,string> as an ICollection<KeyValuePair<int,string>> , and you can access the keys and values as separate collections with the Keys and Values properties.字典实际上是键/值对的集合:您可以将IDictionary<int,string>用作ICollection<KeyValuePair<int,string>> ,并且您可以使用 Keys 和 Values 作为单独的集合访问键和值特性。

Both ICollection and IDictionary are unordered, meaning that although you can retrieve the elements in some order with the CopyTo method or a foreach loop, that order has no special meaning, and it might change for no apparent reason. ICollectionIDictionary都是无序的,这意味着尽管您可以使用CopyTo方法或 foreach 循环以某种顺序检索元素,但该顺序没有特殊意义,并且可能会无缘无故地更改。 That's the main difference between ICollection and IList : a list lets you put items in specific positions, just like an array, and they stay there until you move them.这是ICollectionIList之间的主要区别:列表允许您将项目放在特定位置,就像数组一样,并且它们会一直留在那里直到您移动它们。

List<> and Dictionary<,> - pretty different data structures which used for different purposes, List is simply a set of items and Dictionary is a set of key-value pairs. List<>Dictionary<,> - 用于不同目的的完全不同的数据结构,List 只是一组项目,而 Dictionary 是一组键值对。

Dictionary is pretty useful when you have a set of complex objects and want to have fast access by let's say ObjectName/ObjectId, in this case you create IDictionary<string, TObject> where key would be ObjectId and Value would be an object itself.当您拥有一组复杂对象并希望通过让我们说 ObjectName/ObjectId 进行快速访问时,Dictionary 非常有用,在这种情况下,您创建IDictionary<string, TObject>其中 key 将是 ObjectId 而 Value 将是一个对象本身。

Some differences:一些差异:

  • List persist order of the items, Dictionary does not列出项目的持久顺序,字典不
  • List allow fast access by index列表允许通过索引快速访问
  • List support built in QuickSort algorithm for fast data sorting列表支持内置 QuickSort 算法,用于快速数据排序
  • Dictionary allows ~ O(1) time complexity to access an item (value) by a key字典允许 ~ O(1)时间复杂度通过键访问项目(值)
  • Dictionary<K,V> is an associative array, or map. Dictionary<K,V>是关联数组或映射。 It is a container that can be indexed by values of any type.它是一个可以被任何类型的值索引的容器。
  • List<T> is an integer indexed array. List<T>是一个整数索引数组。 It is a container that is indexed by contiguous integers.它是一个由连续整数索引的容器。

The essential difference therefore is in how the containers are indexed.因此,本质的区别在于容器的索引方式。

Don't fall into the trap of believing that Dictionary<int,T> is semantically equivalent to List<T> .不要陷入相信Dictionary<int,T>在语义上等同于List<T>的陷阱。 The difference is that the indexing of List<T> is contiguous whereas there can be gaps in the indexing for Dictionary<int,T> .不同之处在于List<T>的索引是连续的,而Dictionary<int,T>的索引可能存在间隙

I have a class library which accesses a variety of T-sql sprocs;我有一个访问各种 T-sql 程序的类库; each sproc returns a single row but varying columns.每个 sproc 返回单行但不同的列。 I needed a general purpose solution for an retrieving the values and Dictionary<> provided a much cleaner solution than List<>.我需要一个通用的解决方案来检索值,而 Dictionary<> 提供了一个比 List<> 更简洁的解决方案。

The class common to all of the wrappers declares所有包装器通用的类声明

public Dictionary<string, String> datadict = new Dictionary<string, string>();

and

public Dictionary<string, String> LoadData(string sproc, string paramName, string paramValue)

Invoking a Reader, the datadict is loaded with调用 Reader,datadict 被加载

for (int i = Reader.FieldCount; i != 0; i--)
 {
  datadict.Add(Reader.GetName(i - 1).Trim(), Reader.GetString(i - 1).Trim());
 }

and returns datadict to the calling class which can then retrieve the data much like Reader does;并将 datadict 返回给调用类,然后调用类可以像 Reader 一样检索数据; Eg:例如:

datadict = myData.LoadData("spGetSSN", "", "");
  ssn1 = datadict["SSN1"];
  ssn2 = datadict["SSN2"];
  ssn3 = datadict["SSN3"];

Much cleaner for me that List<>. List<> 对我来说更干净。

Elements in a list have the following characteristics:列表中的元素具有以下特征:

They maintain their ordering unless explicitly re-ordered (for example, by sorting the list).除非明确重新排序(例如,通过对列表进行排序),否则它们会保持其顺序。 They can be of any type, and types can be mixed.它们可以是任何类型,并且类型可以混合。 They are accessed via numeric (zero based) indices.它们通过数字(从零开始)索引访问。 Elements in a Dictionary have the following characteristics:字典中的元素具有以下特征:

Every entry has a key and a value Ordering is not guaranteed Elements are accessed using key values Key values can be of any hashtable type (ie not a dict) and types can be mixed Values can be of any type (including other dict's), and types can be mixed每个条目都有一个键和一个值 不能保证排序 使用键值访问元素 键值可以是任何哈希表类型(即不是字典)并且类型可以混合 值可以是任何类型(包括其他字典),并且类型可以混合

List: In the list, it is possible to add duplicate record.列表:在列表中,可以添加重复记录。

Dictionary: In dictionary key must be unique.字典:字典中的键必须是唯一的。 It is not possible to add duplicate key in dictionary.无法在字典中添加重复键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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