【问题标题】:Is there a way to remove certain duplicates of a list but not others?有没有办法删除列表的某些重复项而不是其他的?
【发布时间】:2020-03-28 20:13:20
【问题描述】:

所以我一直在研究一个非常复杂的列表,该列表由元组字典的一部分组成。这是我的代码。

 var Truth = new Dictionary<Tuple<string, string, string>, bool>

         {
             {new Tuple <string,string,string>("!A","!B","!C"),false },
             {new Tuple <string,string,string>("!A","!B","C"),false },
             {new Tuple <string,string,string>("!A","B","!C"),false },
             {new Tuple <string,string,string>("!A","B","C"),false },
             {new Tuple <string,string,string>("A","!B","!C"),true },
             {new Tuple <string,string,string>("A","!B","C"),true },
             {new Tuple <string,string,string>("A","B","!C"),true },
             {new Tuple <string,string,string>("A","B","C"),true},
         };

         var trueKeyList = Truth.Where(kv => kv.Value).ToList();
        List<string> myList = new List<string>();



        Console.WriteLine("SOP is: ");
        foreach (var keyValue in trueKeyList)
        {

                Console.Write(keyValue.Key.ToString().Trim(new Char[] { ')', '(' }));
                Console.Write(" AND ");
            myList.Add(keyValue.Key.Item1);
            myList.Add(keyValue.Key.Item2);
            myList.Add(keyValue.Key.Item3);


        }
        Console.WriteLine("");


        List<string> lstStrIgnore = new List<string>() { "A!", "B!", "C!" };
        myList = myList.Distinct().Where(x => x != lstStrIgnore).ToList();

在底部附近,您会看到我尝试删除 A B 和 C 的重复项,但不删除 A 的重复项!乙!和 C!。但是这不起作用,因为它说“操作数!= 不能应用于类型字符串和类型列表”无论如何要这样做吗?

【问题讨论】:

  • myList 已经不包含来自lstStrIgnore 的任何项目。如果您有不同的输入,那么var outputList = myList.Except(lstStrIgnore); 就可以了。

标签: c# list linq dictionary tuples


【解决方案1】:
myList.Distinct().Where(x => !lstStrIgnore.Contains(x));

或者如果您想应用自己的比较器/转换为大写/小写等

myList.Distinct().Where(x => !lstStrIgnore.Any(l => l.Equals(x)));

【讨论】:

  • 非常感谢,第二个选项有效。但是还有一个问题,我可能不得不问另一个问题,但是您知道是否可以用一个新元素替换列表中的两个元素?
  • 如果我的答案对您有用,您应该将其标记为答案。至于你的第二个问题 - 如果你想替换列表中的确切节点,然后在序列中找到元素索引,通过 int index = list.IndexOf(b);然后使用 RemoveAt 和 Insert。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多