Dictionary <int,List >

我有这样的事情:

Dictionary<int, List> fileList = new Dictionary<int, List>(); 

然后,我用一些变量填充它,例如:

 fileList.Add( counter, new List { OFD.SafeFileName, OFD.FileName, VERSION, NAME , DATE , BOX , SERIAL_NUM, SERIES, POINT , NOTE , VARIANT } ); 

其中counter是每次发生某事时递增+1的变量, List{XXX}其中XXX是包含一些文本的字符串变量。

我的问题是,如果counter == 1,如何从列表中访问这些字符串?

您可以像正常一样访问字典和列表中的数据。 请记住,首先访问字典中的值,这将返回一个列表。 然后,访问列表中的项目。

例如,您可以索引到返回列表的字典,然后索引到列表中:

  ------ Returns a list from the dictionary | --- Returns an item from the list | | vv fileList[0][0] // First item in the first list fileList[1][0] // First item in the second list fileList[1][1] // Second item in the second list // etc. 

Dictionary使用Indexer通过key访问其vallues。

 List items = fileList[counter]; var str0 = items[0]; var str1 = items[1]; 

然后你可以对列表做任何事情。

FishBasketGordo解释了如何访问数据结构中的条目。 我只会在这里添加一些想法:

字典(基于哈希表)允许快速访问任意键。 但你的密钥是由一个计数器变量给出的(counter = 0,1,2,3,4 ……)。 访问此类密钥的最快方法是简单地使用数组或列表的索引。 因此我只使用List<>而不是Dictionary<,>

此外,您的列表似乎不会列出匿名值,而是列出具有非常特定和不同含义的值。 即日期与名称不同。 在这种情况下,我将创建一个存储这些值的类,并允许单个访问各个值。

 public class FileInformation { public string SafeFileName { get; set; } public string FileName { get; set; } public decimal Version { get; set; } public string Name { get; set; } public DateTime Date { get; set; } ... } 

现在您可以创建一个这样的列表:

 var fileList = new List(); fileList.Add( new FileInformation { SafeFileName = "MyDocument.txt", FileName = "MyDocument.txt", Version = 1.2, ... } } 

你可以访问这样的信息

 decimal version = fileList[5].Version; 

如果键不是从零开始,只需减去起始值:

 int firstKey = 100; int requestedKey = 117; decimal version = fileList[requestedKey - firstKey].Version; 
 Dictionary> fileList = new Dictionary>(); fileList.Add(101, new List { "fijo", "Frigy" }); fileList.Add(102, new List { "lijo", "liji" }); fileList.Add(103, new List { "vimal", "vilma" }); for (int Key = 101; Key < 104; Key++) { for (int ListIndex = 0; ListIndex < fileList[Key].Count; ListIndex++) { Console.WriteLine(fileList[Key][ListIndex] as string); } } 

您可以通过MyDic[Key][0]访问List。 编辑列表时,不会出现任何运行时错误,但会导致在Dictionary中存储不必要的值。 好多了:

  1. MyDict[Key]分配给新列表
  2. 编辑新列表然后
  3. 将新列表重新分配给MyDict[Key]而不是使用List as MyDict[Key]编辑Dictionary中的特定变量。

代码示例:

 List lstr = new List