访问C#字典

本文关键字:字典 访问 | 更新日期: 2024-09-22 07:14:12

我有一个颜色字典,如下所示。

Dictionary<string, List<System.Drawing.Color>> channelColorInformation = 
    new Dictionary<string, List<System.Drawing.Color>>();
List<System.Drawing.Color> colorInfo = new List<System.Drawing.Color>();
System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("#FFF0F8FF");
colorInfo.Add(color);
color = System.Drawing.ColorTranslator.FromHtml("#FFFAEBD7");
colorInfo.Add(color);
color = System.Drawing.ColorTranslator.FromHtml("#FF00FFFF");
colorInfo.Add(color);
channelColorInformation.Add("Channel1", colorInfo);

如何从索引0、1、2处的Channel1的字典中获取System.Drawing.Color信息?

访问C#字典

有两个不同的选项,这取决于字典中缺少条目是否是错误。如果这代表一个错误,您可以使用索引器获取它:

List<Color> colors = channelColorInformation["Channel1"];
// Access the list in the normal way... either with an indexer (colors[0])
// or using foreach

如果没有键"Channel1"的条目,这将引发异常。

否则,使用TryGetValue:

List<Color> colors;
if (channelColorInformation.TryGetValue("Channel1", out colors))
{
    // Use the list here
}
else
{
    // No entry for the key "Channel1" - take appropriate action
}

类似这样的东西:

List<Color> listForChannel1 = channelColorInformation["Channel1"];
Color c1 = listForChannel1[0];    
Color c2 = listForChannel1[2];    
Color c3 = listForChannel1[3];

更新

@Jon的回答也是相关的,因为它显示了两种选项来处理字典中不存在密钥的可能性。

var result = channelColorInformation["Channel1"]

每个列表元素都是一个List<Color>实例,因此您可以使用索引器访问单个项:

List<Color> channel = channelColorInformation["Channel1"];
Color index0 = channel[0];
Color index1 = channel[1];
// etc.