根据查询表为数组元素分配值

时间:2019-04-26 10:09:04

标签: c#

嗨,我正在编写一个c#程序,其中我需要根据查询表和带有元数据的字符串数组集填充一个数组。我的查找表如下所示(带有键的表:发送器,值:接收器的数组)

{
    LED1: ["px1","px2","px3"],
    LED2: ["px4","px5","px6"]
}

和我的元数组看起来像这样(它是动态的。只是一个例子。这是来自数据库查询的响应。)

var transmitters = new string[] { "LED1", "LED2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };

我的要求是

  • 如果查找表中存在发送器LED1或LED2(或任何其他发送器),则必须将发送器的值(即[“ px1”,“ px2”,“ px3”])与接收器进行比较查找中存在的LED和LED必须标记为黄色。
    • 孤立的发送器或接收器必须标记为红色。

示例

查找

{
        LED1: ["px1", "px2", "px3"],
        LED2: ["px5", "px8"]
}

发射器和接收器

var transmitters = new string[] { "led1", "led2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };

结果应为

led1-yellow
px1-yellow
px2-yellow
px3-yellow
led2-yellow
px5-yellow
px4-red
px6-red.

我写的代码行得通

public class Program
{
    public static void Main()
    {
        var transmitters = new string[] { "led1", "led2" };
        var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
        var lookup = new Dictionary<string, string[]>() { { "led1", new string[] { "px1", "px2", "px3" } }, { "led2", new string[] { "px5", "px8" } } };

        var blocks = new List<Block>();
        var blocksTracker = new List<string>();

        foreach (var transmitter in transmitters)
        {
            if (lookup.ContainsKey(transmitter))
            {
                var receiverLookup = lookup[transmitter];
                var intersection = receivers.Intersect(receiverLookup).ToArray();
                if (intersection.Length > 0)
                {
                    blocks.Add(new Block() { Id = transmitter, status = "yellow" });
                    blocksTracker.Add(transmitter);
                    foreach (var receiver in intersection)
                    {
                        blocks.Add(new Block() { Id = receiver, status = "yellow" });
                        blocksTracker.Add(receiver);
                    }
                }
                else
                {
                    blocks.Add(new Block() { Id = transmitter, status = "red" });
                    blocksTracker.Add(transmitter);
                }
            }
        }
    }
}

我是C#的新手,我想知道是否有更好的方法可以做到这一点。请帮忙。您可以看到有效的小提琴Here

0 个答案:

没有答案