简体   繁体   English

C# Integer 列表 Arrays 不包含项目

[英]C# List of Integer Arrays does not Contain Item

My goal is to add an unknown number of integer coordinates to a collection.我的目标是将未知数量的 integer 坐标添加到集合中。 While I can add these coordinates to this list List<int[]> coordList = new List<int[]>();虽然我可以将这些坐标添加到这个列表中List<int[]> coordList = new List<int[]>(); I cannot check if coordList.Contains(specifiedCoordinate) .我无法检查coordList.Contains(specifiedCoordinate)是否。

This is what I have so far:这是我到目前为止所拥有的:

List<int[]> coordList = new List<int[]>();
coordList.Add(new int[] {1, 3});
coordList.Add(new int[] {3, 6});
bool contains = coordList.Contains(new int[]{1, 3})
Console.WriteLine(contains);

However, contains is always false even though I specify the same values that I add.但是,即使我指定了与我添加的相同的值, contains也始终为false I have tried ArrayList as a possible alternative, but the results are the same as using List .我已尝试ArrayList作为可能的替代方案,但结果与使用List相同。

If there's something I'm not understanding or if there's an alternative, I'm all ears.如果有什么我不理解的或者有替代的,我会全神贯注。

It seems like you want:看起来你想要:

bool contains = coordList.Any(a => a.SequenceEqual(new int[]{1, 3}));

SequenceEqual docs . SequenceEqual 文档

.Any and .SequenceEqual are extension methods provided by the System.Linq namespace. .Any.SequenceEqualSystem.Linq命名空间提供的扩展方法。 You may need to ensure that you have using System.Linq;您可能需要确保using System.Linq; at the top of your code file to make this work.在您的代码文件的顶部,以使这项工作。

If you'd use value tuples, you'd get the value-comparison for free, also the code gets neater:如果您使用值元组,您将免费获得值比较,代码也变得更简洁:

        var coordList = new List<(int x, int y)>();
        coordList.Add((1, 3));
        coordList.Add((3, 6));
        //contains is now true because 
        //value tuples do value comparison in their 'Equals' override 
        bool contains = coordList.Contains((1, 3));
        Console.WriteLine(contains);

From OP来自 OP

Answer回答

So, I created a new function based on Llama's suggestion:所以,我根据 Llama 的建议创建了一个新的 function:

static bool ContainsCoordinate(int[] coords, List<int[]> coordList) {
    bool contains = coordList.Any(a => a.SequenceEqual(coords));
    return contains;
}

Which just works a charm.这只是一种魅力。

I would also like to thank Ron Beyer for helping me understand more about object declaration and instancing,我还要感谢 Ron Beyer 帮助我更多地了解 object 声明和实例化,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM