次の方法で共有


Memcmp in C#

I confess that, for some years now, I've wondered what the managed equivalent of memcmp() was, usually when I wanted to compare two byte arrays for equality. It turns out that Linq provides a SequenceEquals() extension method which does exactly what I want:

using System;
using System.Linq;

namespace SequenceEquals
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] a = new byte[] { 1, 2, 3 };
            byte[] b = new byte[] { 4, 5, 6 };
            byte[] c = new byte[] { 1, 2, 3 };
            byte[] d = new byte[] { 1, 2 };

            Console.WriteLine("{0}", a.SequenceEqual(a));
            Console.WriteLine("{0}", a.SequenceEqual(b));
            Console.WriteLine("{0}", a.SequenceEqual(c));
            Console.WriteLine("{0}", a.SequenceEqual(d));
        }
    }

The code above gives True, False, True, False.

Comments

  • Anonymous
    January 01, 2009
    Mono.Rocks also has a .SequenceCompare() extension method which does a lexicographical compare.

  • Anonymous
    January 02, 2009
    The comment has been removed