Comparing two string arrays in C#

你离开我真会死。 提交于 2019-12-01 02:02:56

You can use Linq:

bool areEqual = a.SequenceEqual(b);

Try using Enumerable.SequenceEqual:

var equal = Enumerable.SequenceEqual(a, b);

If you want to compare them all in one go:

string[] a = { "The", "Big", "Ant" };
string[] b = { "Big", "Ant", "Ran" };
string[] c = { "The", "Big", "Ant" };
string[] d = { "No", "Ants", "Here" };
string[] e = { "The", "Big", "Ant", "Ran", "Too", "Far" };

// Add the strings to an IEnumerable (just used List<T> here)
var strings = new List<string[]> { a, b, c, d, e };

// Find all string arrays which match the sequence in a list of string arrays
// that doesn't contain the original string array (by ref)
var eq = strings.Where(toCheck => 
                            strings.Where(x => x != toCheck)
                            .Any(y => y.SequenceEqual(toCheck))
                      );

Returns both matches (you could probably expand this to exclude items which already matched I suppose)

if you want to get array data that differ from another array you can try .Except

string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "aa" };

string[] DifferArray = array1.Except(array2).ToArray();

Output: {"bb","cc"}

        if (a.Length == d.Length)
        {
            var result = a.Except(d).ToArray();
            if (result.Count() == 0)
            {
                Console.WriteLine("OK");
            }
            else
            {
                Console.WriteLine("NO");
            }
        }
        else
        {
            Console.WriteLine("NO");
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!