字典查找 - 特定字符串

时间:2013-01-15 11:34:37

标签: c# .net dictionary tuples

我想控制512个DMX通道中的颜色(在本例中为“红色”)。我从XML文件中读取红色并将其放在字典中:

<Channel Id="Lamp1Red" Key="2"/>
<Channel Id="Lamp1Green" Key="3"/>
<Channel Id="Lamp1Blue" Key="4"/>
<Channel Id="Lamp2Red" Key="5"/>
<Channel Id="Lamp2Green" Key="6"/>
<Channel Id="Lamp2Blue" Key="7"/>
<Channel Id="Lamp3Red" Key="8"/>
        etc. ... up to 512 keys/channels.

我有以下Dictionary,其中包含ID(字符串)和频道(键+值)

public Dictionary<string, Tuple<byte, byte>> DmxChannelsDictionary
{
    get;
    set;
}

我想查找包含ID“LampXRed”的所有字符串(红色)并获取每个字符串的密钥(2,5,8)并在以下方法中使用它们SetColor:

SetColor(red, green, blue);
public void SetColor(Tuple<byte, byte> redTuple, Tuple<byte, byte> greenTuple, Tuple<byte, byte> blueTuple)

SetColor将元组传递给DmxDataMessage()

public static byte[] DmxDataMessage(Tuple<byte, byte>  redTuple, Tuple<byte, byte> greenTuple, Tuple<byte, byte> blueTuple)
    {
        //Initialize DMX-buffer: Must be full buffer (512Bytes)
        var dmxBuffer = new byte[512];
        dmxBuffer.Initialize();

        // Fill DATA Buffer: Item1 (Key/Channel) = Item2 (Value)
        // Channel1
        dmxBuffer[redTuple.Item1] = redTuple.Item2;
        dmxBuffer[greenTuple.Item1] = greenTuple.Item2;
        dmxBuffer[blueTuple.Item1] = blueTuple.Item2;

        // Here I need a foreach or something else to set the the value for each channel (up to 512)
       ....

如何在字典中进行智能搜索/交互并保存所有红色ID +密钥以便在SetColor()中使用???

这是我为一个“红色”频道所做的方式:

var red = DmxChannelsDictionary["Lamp1Red"];
red = Tuple.Create(red.Item1, _redValue); // _redValue = 0-255

我希望这是有道理的。非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

为什么不这样:

class LampInfo
{
  int Red{get;set;}
  int Green{get;set;}
  int Blue{get;set;}
}

然后将灯名称(例如Lamp1)映射到它:

Dictionary<string,LampInfo> dmxChannelsDictionary;

要填充你这样做的东西:

然后你可以这样做:

Lamp lamp=new LampInfo(){Red=2, Green=3, Blue=4}'
dmxChannelsDictionary.Add("Lamp1",lamp);

然后获取您只需说出的数据:

var lamp=dmxChannelsDictionary["Lamp1"];
int red=lamp.Red;

答案 1 :(得分:0)

以下解决了我的问题 - 非常感谢您的帮助。

public static byte[] DmxDataMessage(Tuple<byte, byte> redTuple, Tuple<byte, byte> greenTuple, Tuple<byte, byte> blueTuple, EnttecDmxController _enttecDmxControllerInterface)
{

    foreach (KeyValuePair<string, Tuple<byte, byte>> entry in _enttecDmxControllerInterface.DmxChannelsDictionary)
    {
        if (entry.Key.Contains("Red"))
        {
            dmxBuffer[entry.Value.Item1] = redTuple.Item2;
        }
    }
     .......
}