通过另一个keyvalue列表减去keyvalue列表

时间:2017-12-18 11:12:51

标签: c# list linq

有没有办法通过linq做事情而不必进行嵌套for循环和检查密钥(即下面)

假设:每个列表都不包含重复日期

foreach(KeyValuePair value1 in List1)
{
   foreach(KeyValuePair value2 in List2)
   {
        if(value1.Key == Value2.Key)
        {
            .........
        }
        else
        {
           ......
        }
   }
}

我有两个列表

的List1

DateTime, Value
2017/01/01, 5
2017/01/02, 10
2017/01/05, 15

列表2

DateTime, Value
2017/01/01, 1
2017/01/03, 3
2017/01/04, 5

结果需要(列表1 - 列表2)

DateTime, Value
2017/01/01, 4
2017/01/02, 10
2017/01/03, -3
2017/01/04, -5
2017/01/05, 15

2 个答案:

答案 0 :(得分:3)

如果您想从<form id="form" method="get" action="/download"> <input type="hidden" id="fileName" name="fileName" value="Test.doc"/> </form> 中减去list2(即加起来list1否定 list1):

list2

答案 1 :(得分:1)

我认为,在您的情况下,您可以使用loop代替Linq。此外,它不会像你提到的那样嵌套;

        var listA = new List<KeyValuePair<DateTime, int>>()
        {
            new KeyValuePair<DateTime, int>(new DateTime(2017,01,01),15),
            new KeyValuePair<DateTime, int>(new DateTime(2017,01,02),15),
            new KeyValuePair<DateTime, int>(new DateTime(2017, 01, 04), 15),
            new KeyValuePair<DateTime, int>(new DateTime(2017, 01, 05), 15)
        };
        var listB = new List<KeyValuePair<DateTime, int>>()
        {
            new KeyValuePair<DateTime, int>(new DateTime(2017, 01, 01), 10),
            new KeyValuePair<DateTime, int>(new DateTime(2017, 01, 03), 15)
        };
        var listC = new List<KeyValuePair<DateTime, int>>();
        var maxCount = Math.Max(listA.Count, listB.Count);
        for (int i = 0; i < maxCount; i++)
        {
            if (listA.Count < i + 1)
            {
                listC.Add(new KeyValuePair<DateTime, int>(listB[i].Key,-listB[i].Value));
                continue;
            }
            if (listB.Count < i + 1)
            {
                listC.Add(new KeyValuePair<DateTime, int>(listA[i].Key, listA[i].Value));
                continue;
            }
            if (listA[i].Key == listB[i].Key)
            {
                int value = listA[i].Value - listB[i].Value;
                listC.Add(new KeyValuePair<DateTime, int>(listA[i].Key, value));
            }
            else
            {
                listC.Add(new KeyValuePair<DateTime, int>(listA[i].Key, listA[i].Value));
                listC.Add(new KeyValuePair<DateTime, int>(listB[i].Key, -listB[i].Value));
            }
        }
相关问题