如何检查List <list <int >>是否包含List <int>

时间:2019-05-29 10:05:02

标签: c# list

我有一个List<List<int>>,我想在其中插入新的List<int>。我想在添加新的List<int>之前检查一下新的List<List<int>>

例如

List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();

我已经尝试过

MaterList.Contains, MasterList.Any 

但没有任何帮助

例如

MasterList(1)=1,2,3
MasterList(2)=4,5

但是当我看到1,2,3或4,5再次出现时,不想输入它,因为它们已经在MasterList中某个位置了

5 个答案:

答案 0 :(得分:6)

您可以使用Linq的SequenceEqual

if (MasterList.Any(c => c.SequenceEqual(childList)))
{
    //contains

}

答案 1 :(得分:0)

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

        List<int> childList1 = new List<int>() { 1, 2, 3 };
        List<int> childList2 = new List<int>() { 4, 5 };

        MasterList.Add(childList1);
       //  MasterList.Add(childList2);

        Console.WriteLine(MasterList.Contains(childList1));
        Console.WriteLine(MasterList.Contains(childList2));
        Console.WriteLine(MasterList[0].Contains(1));
        Console.WriteLine(MasterList[0].Contains(7));
//True
//False
//True
//False

也许我不明白您的问题,对不起。

答案 2 :(得分:0)

您可以像这样比较两个列表是否相等:

class Plugin():
    plugins = []

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if getattr(cls, 'do_something') is getattr(__class__, 'do_something'):
            print("Warning: Your plugin might not work, missing 'do_something'")
        else:
            __class__.plugins.append(cls())

    def do_something(self):
        ...

class Render(Plugin):
    def __init__(self):
        print("Render init")

for plugin in Plugin.plugins:
    plugin.do_something()

现在,使用此功能,您可以使用Linq函数搜索匹配列表:

bool AreListsIdentical(List<int> lhs, List<int> rhs)
{
    if(lhs.Count != rhs.Count) return false;

    return lhs.Zip(rhs, (l,r) => l == r).All(value => value);
}

答案 3 :(得分:0)

我测试了以下内容,并且有效:

           List<List<int>> masterList = new List<List<int>>() {
                new List<int>() { 1, 2, 3},
                new List<int>() { 1, 2},
                new List<int>() { 1, 2, 3, 4},
                new List<int>() { 1, 2, 5},
                new List<int>() { 1, 3, 7},
                new List<int>() { 2, 3, 4},
                new List<int>() { 1, 5, 8},
                new List<int>() { 1, 4, 9}
            };

            List<int> newList = new List<int>() { 1,2,5};
            Boolean contains = masterList.Any(x => (x.Count() == newList.Count()) && (x.Select((y, i) => y == newList[i]).All(y => y)));

答案 4 :(得分:0)

这种方式:

List<List<int>> listOfIntLists = new List<List<int>>() {
    new List<int>(){ 1,2 },
    new List<int>(){ 3,4 },
    new List<int>(){ 5,6 }
};

List<int> integers = new List<int>() { 1, 2 };

if(listOfIntLists.Any(x => x.All(y => integers.Any(z => z == y))) == false)
{
    listOfIntLists.Add(integers);
}
相关问题