获取另一个列表与重复项的差异的列表方法(listobject.Expect 方法不起作用)

List method to get difference of another list with duplicates (listobject.Expect method does not work)

有两个列表。我需要差价

List<int> list1 = new List<int>() {18, 13, 22, 24, 20, 20, 27, 31, 25, 28 };
List<int> list2 = new List<int>() {18, 13, 22, 24, 20, 20, 20, 27, 31, 25, 28, 86, 78, 25 };

var listDif = list2.Except(list1);

foreach (var s in listDif)
Console.WriteLine(s);
Console.Read();

答案应该是 20, 86,78, 25 但它只输出 86,78

因为你只检查 list1 中的哪些数字在 list2 中丢失了 但是你需要检查 list2 中的哪些数字不存在于 list1listDif。 你可以做到

    List<int> diff = new List<int>();

    foreach (int num in list1)
    {
       if (!list2.Contains(num))
       {
         diff.Add(num);
       }
    }

    foreach (int num in list2)
    {
       if (!list1.Contains(num) && !diff.contains(num))
       {
          diff.Add(num);
       }
    }

如果您确实想要那种行为,您应该试试这个:

List<int> list1 = new List<int>() { 18, 13, 22, 24, 20, 20, 27, 31, 25, 28 };
List<int> list2 = new List<int>() { 18, 13, 22, 24, 20, 20, 20, 27, 31, 25, 28, 86, 78, 25 };

// Remove elements of first list from second list
list1.ForEach(l => list2.Remove(l));
list2 = list2.Distinct().ToList();

list2.ForEach(d => Console.WriteLine(d));
Console.Read();

这很好用:

  1. 复制 list2
  2. list2
  3. 中删除 list1

代码示例:

List<int> list1 = new List<int>() { 18, 13, 22, 24, 20, 20, 27, 31, 25, 28 };
List<int> list2 = new List<int>() { 18, 13, 22, 24, 20, 20, 20, 27, 31, 25, 28, 86, 78, 25 };

var diff = list2;
list1.All(x => diff.Remove(x));

您也可以在 list2 上执行 Remove,但是,这会修改 list2