📜  c# 列表项不在另一个列表中 - C# (1)

📅  最后修改于: 2023-12-03 15:13:50.644000             🧑  作者: Mango

C# 列表项不在另一个列表中 - C#

在 C# 中,我们经常需要比较两个列表,并找出不在其中一个列表中的项。这在处理数据集合、列表筛选和数据操作中非常常见。本文将介绍几种方法来实现这一功能。

方法一:使用 LINQ 查询

使用 LINQ (Language-Integrated Query) 是一种简洁高效的方法来处理集合数据。以下是使用 LINQ 查询来找出不在另一个列表中的项的示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };

        List<int> difference = list1.Except(list2).ToList();

        Console.WriteLine("List1: " + string.Join(", ", list1));
        Console.WriteLine("List2: " + string.Join(", ", list2));
        Console.WriteLine("Items in List1 but not in List2: " + string.Join(", ", difference));
    }
}

输出结果:

List1: 1, 2, 3, 4, 5
List2: 3, 4, 5, 6, 7
Items in List1 but not in List2: 1, 2
方法二:使用迭代循环

另一种方法是使用两个嵌套的迭代循环来比较列表。以下是使用迭代循环来找出不在另一个列表中的项的示例代码:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };

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

        foreach (int item in list1)
        {
            bool found = false;

            foreach (int otherItem in list2)
            {
                if (item == otherItem)
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                difference.Add(item);
            }
        }

        Console.WriteLine("List1: " + string.Join(", ", list1));
        Console.WriteLine("List2: " + string.Join(", ", list2));
        Console.WriteLine("Items in List1 but not in List2: " + string.Join(", ", difference));
    }
}

输出结果与方法一相同:

List1: 1, 2, 3, 4, 5
List2: 3, 4, 5, 6, 7
Items in List1 but not in List2: 1, 2
方法三:使用 HashSet

HashSet 是一种集合类型,它可以高效地存储和检索数据。我们可以将一个列表转换为 HashSet,并使用集合操作来找出不在另一个列表中的项。以下是使用 HashSet 来找出不在另一个列表中的项的示例代码:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };

        HashSet<int> set2 = new HashSet<int>(list2);
        List<int> difference = new List<int>();

        foreach (int item in list1)
        {
            if (!set2.Contains(item))
            {
                difference.Add(item);
            }
        }

        Console.WriteLine("List1: " + string.Join(", ", list1));
        Console.WriteLine("List2: " + string.Join(", ", list2));
        Console.WriteLine("Items in List1 but not in List2: " + string.Join(", ", difference));
    }
}

输出结果同样是:

List1: 1, 2, 3, 4, 5
List2: 3, 4, 5, 6, 7
Items in List1 but not in List2: 1, 2

以上就是几种在 C# 中找出一个列表中不在另一个列表中的项的方法。可以根据实际需求选择使用 LINQ 查询、迭代循环或 HashSet。希望本文对你有所帮助!