Comparing two string arrays in C#

前端 未结 5 537
暖寄归人
暖寄归人 2021-01-07 16:18

Say we have 5 string arrays as such:

string[] a = {\"The\",\"Big\", \"Ant\"};
string[] b = {\"Big\",\"Ant\",\"Ran\"};
string[] c = {\"The\",\"Big\",\"Ant\"};         


        
相关标签:
5条回答
  • 2021-01-07 16:34
            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");
            }
    
    0 讨论(0)
  • 2021-01-07 16:39

    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)

    0 讨论(0)
  • 2021-01-07 16:45

    Try using Enumerable.SequenceEqual:

    var equal = Enumerable.SequenceEqual(a, b);
    
    0 讨论(0)
  • 2021-01-07 16:47

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

    0 讨论(0)
  • You can use Linq:

    bool areEqual = a.SequenceEqual(b);
    
    0 讨论(0)
提交回复
热议问题