The current solution works in a specific context, but there is further room for potential error. Without sorting the list, we should not assume a specific order; even if we have set it up in that way. Unaccounted logic or later changes may alter the order in one of the lists, which results in a false negative when comparing the elements of each list using a single index value.

The solution is fairly simple. Just sort the list, before you compare values in it. This is straight forward, if we are using List<int>; int values already know how to sort themselves, in a list. If we ever want the same functionality from a List<t> of custom types, we need to make use of the System.IComparable<in t> interface.


Sorting a List<t>

We sort a List<t> with the method List<t>.Sort(). Sorting both lists before comparing values guarantees that if the lists both contain the same set of values, they will also be in the same order.

private bool DoListsMatch(List<int> list1, List<int> list2)
{
    var areListsEqual = true;

    if (list1.Count != list2.Count)
        return false;

    list1.Sort(); // Sort list one
    list2.Sort(); // Sort list two

    for (var i = 0; i < list1.Count; i++)
    {
        if (list2[i] != list1[i])
        {
            areListsEqual = false;
        }
    }

    return areListsEqual;
}

Using System.IComparable<in t> to make custom types compatible with List<t>.Sort()

Should we want to perform the same function on a list that contains custom types, we need to add the System.IComparable<in t> interface to that type. This interface only contains one method that needs to be implemented in the class - public int CompareTo(t other). This method compares the local type with the other type, and returns an int value representing the the placement of the local type in comparison to the other type.

For the example, I will simply use a custom class that stores an int. You can set this CompareTo() method up in any way you like, specific to the types you use inside that class. You may want to compare ID numbers, or compare distances to a particular position, or even a given name.

class MyInt : IComparable<MyInt>
{
    int value;

    public int CompareTo(MyInt other)
    {
        return value.CompareTo(other.value);
    }
}

private bool DoListsMatch(List<MyInt> list1, List<MyInt> list2)
{
    // ...
}

As a final note, with the use of a custom implementation of int CompareTo(t other), it is worth considering the possibility of error if two unique t values can still compare with each-other as equal. If the same two values would not return a value of true when compared as valueA == valueB1, there is still a possibility of incorrect output, when comparing both lists. If CompareTo() returns a value of 0, the items will not sort in any particular order (in relation to eachother), in the list. As such, we can not guarantee the order of the list1.

1 If the two items also return true when compared using the == operator, the previous checks will still correctly identify the objects as equal, and this will be a non-event.


Answer from Gnemlock on Stack Exchange
🌐
Unity
discussions.unity.com › archived forums › questions & answers
How do I compare two lists in C# - Questions & Answers - Unity Discussions
September 15, 2016 - Hi, I’ve been doing a pretty basic “Simon says” game and Im kinda stuck on a problem: I’m saving the color order as numbers in an int list to compare them later with user color picks while is playing. I’ve tried to comp…
🌐
Unity
discussions.unity.com › unity engine
Comparing two lists with duplicates? - Unity Engine - Unity Discussions
December 15, 2020 - I have two lists that hold a scriptableobject type (ItemData). I want to check if they contain the same elements of ItemData. Order does not matter, however duplicates does matter. Example 1 List 1: Apple, Banana, App…
Discussions

unity - Check if two lists are the same - Game Development Stack Exchange
I'm currently trying to make a crafting system. For a little background I have a json file with crafting recipes. I check each of these recipes against the items I have in another list which holds ... More on gamedev.stackexchange.com
🌐 gamedev.stackexchange.com
February 11, 2017
compare two lists regardless of order Unity c# - Stack Overflow
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 CheckMa... More on stackoverflow.com
🌐 stackoverflow.com
c# - Unity how to compare contents of two arrays regardless of order? - Stack Overflow
Looking for the most efficient way. I found this on comparing lists regardless of order: https://answers.unity.com/questions/1307074/how-do-i-compare-two-lists-for-equality-not-caring.html What ab... More on stackoverflow.com
🌐 stackoverflow.com
How do I compare two lists in C# - Questions & Answers - Unity Discussions
Hi, I’ve been doing a pretty basic “Simon says” game and Im kinda stuck on a problem: I’m saving the color order as numbers in an int list to compare them later with user color picks while is playing. I’ve tried to compare them through two for loops but it just doesn’t work. More on answers.unity.com
🌐 answers.unity.com
0
September 15, 2016
🌐
Stack Exchange
gamedev.stackexchange.com › questions › 137112 › compare-lists-in-unity3d-c
unity - Compare Lists in Unity3D/C# - Game Development Stack Exchange
February 9, 2017 - This method will return true if the two lists are the same length and the corresponding elements are equal according to their default equality comparer. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 1 Way to deserialized or load last save state scene with GameObject and other classes instead of storing normal fields via binary format? 0 Problem using Event Trigger Unity to change bool , but bool keeps setting back to false
Top answer
1 of 2
3

The current solution works in a specific context, but there is further room for potential error. Without sorting the list, we should not assume a specific order; even if we have set it up in that way. Unaccounted logic or later changes may alter the order in one of the lists, which results in a false negative when comparing the elements of each list using a single index value.

The solution is fairly simple. Just sort the list, before you compare values in it. This is straight forward, if we are using List<int>; int values already know how to sort themselves, in a list. If we ever want the same functionality from a List<t> of custom types, we need to make use of the System.IComparable<in t> interface.


Sorting a List<t>

We sort a List<t> with the method List<t>.Sort(). Sorting both lists before comparing values guarantees that if the lists both contain the same set of values, they will also be in the same order.

private bool DoListsMatch(List<int> list1, List<int> list2)
{
    var areListsEqual = true;

    if (list1.Count != list2.Count)
        return false;

    list1.Sort(); // Sort list one
    list2.Sort(); // Sort list two

    for (var i = 0; i < list1.Count; i++)
    {
        if (list2[i] != list1[i])
        {
            areListsEqual = false;
        }
    }

    return areListsEqual;
}

Using System.IComparable<in t> to make custom types compatible with List<t>.Sort()

Should we want to perform the same function on a list that contains custom types, we need to add the System.IComparable<in t> interface to that type. This interface only contains one method that needs to be implemented in the class - public int CompareTo(t other). This method compares the local type with the other type, and returns an int value representing the the placement of the local type in comparison to the other type.

For the example, I will simply use a custom class that stores an int. You can set this CompareTo() method up in any way you like, specific to the types you use inside that class. You may want to compare ID numbers, or compare distances to a particular position, or even a given name.

class MyInt : IComparable<MyInt>
{
    int value;

    public int CompareTo(MyInt other)
    {
        return value.CompareTo(other.value);
    }
}

private bool DoListsMatch(List<MyInt> list1, List<MyInt> list2)
{
    // ...
}

As a final note, with the use of a custom implementation of int CompareTo(t other), it is worth considering the possibility of error if two unique t values can still compare with each-other as equal. If the same two values would not return a value of true when compared as valueA == valueB1, there is still a possibility of incorrect output, when comparing both lists. If CompareTo() returns a value of 0, the items will not sort in any particular order (in relation to eachother), in the list. As such, we can not guarantee the order of the list1.

1 If the two items also return true when compared using the == operator, the previous checks will still correctly identify the objects as equal, and this will be a non-event.


2 of 2
1

This worked for me:

private bool DoListsMatch(List<int> list1, List<int> list2)
{
    var areListsEqual = true;

    if (list1.Count != list2.Count)
        return false;

    for (var i = 0; i < list1.Count; i++)
    {
        if (list2[i] != list1[i])
        {
            areListsEqual = false;
        }
    }

    return areListsEqual;
}
🌐
Unity
answers.unity.com › questions & answers
Comparing two lists to find the difference - Questions & Answers - Unity Discussions
June 13, 2018 - So I am shooting coloured darts at a spinning board. When the dart hits the board it will perform a check using Physics2D.OverlapCircleAll for any nearby darts which are of the same colour. If there are any detected it will add them to a list called Links. I want to be able to compare the other dart’s Link list with the current dart and if there is any differences to be able to add that to the current list.
Find elsewhere
🌐
Unity
answers.unity.com › questions & answers
Comparing list values - Questions & Answers - Unity Discussions
October 15, 2015 - Hi guys! So I need your help, I have created this list, and I’m trying to avoid inserting duplicated values. I’ve already tried some options but this isn’t going that well. So it would be awesome if you could lend me a hand! So here it goes the list class public class Eating_Progress : IComparable { public int Fruit_X; public int Fruit_Y; public int Fruit_Z; public Eating_Progress(int F_X, int F_Y, int F_Z) { Fruit_X = F_X; Fruit_Y = F_Y; ...
🌐
Stack Overflow
stackoverflow.com › questions › 23804881 › how-to-compare-order-of-the-objects-of-list-in-unity
c# - How to compare order of the objects of list in unity - Stack Overflow
What you want is to compare each object directly, and since they are of the same length, you can do that in one loop. UnityScript · import System.Collections.Generic; ... function listsEqual(a : List.<GameObject>, b : List.<GameObject>)//I am assuming that GameObject is the type, but it could be different { for (var i = 0; i < a.Count; i++) { if (a[i] != b[i]) { return false; } } return true; } C# bool ListsEqual(List<GameObject> a, List<GameObject> b)//I am assuming that GameObject is the type, but it could be different { for (var i = 0; i < a.Count; i++) { if (a[i] != b[i]) { return false; } } return true; } Then you can simply implement it like: if (listsEqual(gems, gems1)) { //code goes here } Share ·
🌐
Unity
discussions.unity.com › archived forums › questions & answers
How do I compare two lists for equality (not caring about order) C# - Questions & Answers - Unity Discussions
February 1, 2017 - I have two lists and I want them to be checked to see if they have the same elements. I also want to ignore the order of the two lists. I just want it to check if they contain the same values.
🌐
Unity
discussions.unity.com › archived forums › questions & answers
Compare two Lists and get the items that are not in both lists - Questions & Answers - Unity Discussions
March 11, 2014 - Having two lists (LIST<>), how can I compare two Lists get the items that not in both lists , I know I probably need to use LINQ and I have been trying to learn about it but I’m not good enough with it yet. I have two l…
🌐
Unity
discussions.unity.com › archived forums › questions & answers
How to check if one list contains a matching item from a second list, not in order - Questions & Answers - Unity Discussions
August 26, 2023 - I am trying to compare the items in my player inventory to see if any match the objective items on my active quests list. Basically, I need to compare the items in two lists, but not in order (since the player will obvi…
🌐
Reddit
reddit.com › r/unity3d › list of gameobjects so i can efficiently compare their values/stats?
r/Unity3D on Reddit: List of gameobjects so I can efficiently compare their values/stats?
April 22, 2018 -

I want to create a list of references to "cell" gameobjects and some of their values; such as metabolismRate(int), individualID(string), speciesID(string), red(float), green(float), blue(float).

The cell gameobject has many more values but I only need to keep a reference to each individual cell (whether that should be a reference to the instance of the gameobject or its script i'm not sure) and some of its values (such as the ones mentioned).

Script looks like this:

 public class CellScript : MonoBehaviour {

public int metabolismRate;
public string individualID;
public string speciesID;
public float red;
public float green;
public float blue;
//Many more values...

void Start () {
	//1 -- Chance to mutate values
    //2 -- Add self to list in ManagerObject...
    //...along with certain values for comparison against other individuals
}

void Update () {
	//1 -- Chance to instantiate a new instance of itself
}
 } 

I want to keep the list/dictionary inside a manager script. I already have a list of cell gameobjects (inside a manager) which I can use to keep track of the population size of all cells with list.Count but but am having it hard thinking about how to approach comparing the values of individuals inside that list, to do things like:

  • find how many individuals there are with the speciesID of "ay47i"

  • find how many individuals have a metabolism rate of 5 or more

Any anyone could chime in or point me in the right direction i'd really appreciate it -- or let me know if what i'm trying to achieve isn't clear.

🌐
Unity
discussions.unity.com › unity engine
List comparison returns false even though the lists are identical - Unity Engine - Unity Discussions
September 17, 2020 - I use two lists (int) in my game; lampOrder and playersGivenOrder. The lampOrder list is randomly generated and the other one is empty. When the player touches something in the game, an event is invoked with the id of the object touched. This will be stored in the playersGivenOrder list.
🌐
Unity
discussions.unity.com › questions & answers
Need help comparing arrays/lists to show items that are missing from one of them - Questions & Answers - Unity Discussions
April 9, 2019 - Seems like I’m having a pretty good mental block. For whatever reason I can’t get my head wrapped around this. I need to compare the contents of one array, which contains all possible items (in this case, only 10 items). As the player plays the game, they will collect these items and they ...