Comparing two string arrays in C#

我的未来我决定 提交于 2019-11-30 22:20:19

问题


Say we have 5 string arrays as such:

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"};

Is there a method to compare these strings to each other without looping through them in C# such that only a and c would yield the boolean true? In other words, all elements must be equal and the array must be the same size? Again, without using a loop if possible.


回答1:


You can use Linq:

bool areEqual = a.SequenceEqual(b);



回答2:


Try using Enumerable.SequenceEqual:

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



回答3:


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)




回答4:


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"}




回答5:


        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");
        }


来源:https://stackoverflow.com/questions/17212254/comparing-two-string-arrays-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!