简体   繁体   中英

Compare two char[] arrays in C#

I have the following C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] st = "stackoverflow".ToCharArray();
            char[] ca = { 's', 't', 'a', 'c', 'k' };
            if (st.Take(5) == ca)
            {
                Console.WriteLine("Success");
            }
            else
            {
                Console.WriteLine("Failure");
            }
        }
    }
}

It's intended to write "Success" to the console but it always prints "Failure". Any help would be really appreciated.

== only compares the references of the two arrays, not their items, and since the two arrays have two different references, your comparison will always return false .

You have to compare the elements of one array to the elements of the other. You can use SequenceEqual to accomplish this.

if (st.Take(5).SequenceEqual(ca))
{
    Console.WriteLine("Success");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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