Home > database >  compare two lists regardless of order Unity c#
compare two lists regardless of order Unity c#

Time:08-20

I would like to compare two lists. If both lists have the same number of elements, the same elements, but in a different order. They should be true, is there a way to achieve this?

    bool CheckMatch()
    { 
            if (prueba1 == null && prueba2 == null)
            {
                return true;
            }
            else if (prueba1 == null || prueba2 == null)
            {
                return false;
            }

        if (prueba1.Count != prueba2.Count)
        {

            return false;
        }
        for (int i = 0; i < prueba1.Count; i  )
        {
            for (int j = 0; j < prueba2.Count; j  )
            {
                if (prueba1[i] != prueba2[j])
                    return false;
            }
        }
        return true;        
    }

CodePudding user response:

Sort first and comprare elements

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ABCD : MonoBehaviour
{
    public void Test()
    {
        List<int> A = new List<int>() { 1, 3, 5 };
        List<int> B = new List<int>() { 5, 3, 1 };
    }

    bool IsSame(List<int> A, List<int> B)
    {
        if (A.Count != B.Count)
        {
            return false;
        }

        List<int> ASort = A.ToList();
        ASort.Sort();
        List<int> BSort = B.ToList();
        BSort.Sort();

        for (int i = 0; i < ASort.Count; i  )
        {
            if(ASort[i] != BSort[i])
            {
                return false;
            }
        }

        return true;
    }
}

CodePudding user response:

Not sure how it compares to presorting in regards to the performance, but you can use the Contains method of the list to check for elements

bool Equal(List<T> listA, List<T> listB){
  bool equal = true;
  foreach(var element in listA){
    if(!listB.Contains(element)){
      equal = false;
      break;
    }
  }
  return equal;
}

Note that count of both lists isn't compared as it was assumed that they are equal.

  • Related