- Home /
how to compare the order of the objects of list
I have two lists named gems and gems1 in which I have 16 clones of an object, and they are stored with unique names in both lists. Afterward one list gets shuffled. Now I want to compare the order of the objects in both . How do I do that..??
for(int a=GridHeight;a>0;a--){
for(int b=0;b<GridWidth;b++)
{
g = Instantiate(gemprefab, new Vector3 ( b,a, 0), Quaternion.identity) as GameObject;
g.name= "gem"+ t;
g.transform.parent = gameObject.transform;
LastGem=g.GetComponent<Gem>();
gems1.Add(LastGem);
gemComponent = g.GetComponent<Gem>();
gems.Add(gemComponent);
t++;
}
for(int i = 0; i < gems.Count; i++) {
Vector3 temp = gems[i].transform.position;
randomIndex = Random.Range(0, gems.Count);
gems[i].transform.position = gems[randomIndex].transform.position;
gems[randomIndex].transform.position = temp;
//print (gems[i]);
//print (gems1[i]);
}
}
void comp()
{
for (int i = 0; i < gems.Count; i++) {
for (int j = 0; j< gems1.Count; j++) {
if(gems[i].transform.name.StartsWith(gems1[j].transform.name))
{
break;
//print ("gems[i].transform.name");
//print ("gems1[i].transform.name");
}
}
What do you want to compare ? If the list gems1 is contained in the list gems ? Or if the order is the same ?
If you're trying to check for INDENTICAL LISTS you could do
if(gems === gems1)
@ tw1st3d you mean i can write it as:
for (int i = 0; i < gems.Count; i++)
{
for (int j = 0; j< gems1.Count; j++)
{
if(gems[i]!=gems1[j])
{
break;
}else{
Application.LoadLevel("level02");
}
}
}
No, he told you to use "===" ins$$anonymous$$d of your two for loops. Your 20 lines of code could be replaced by only one.
Answer by Landern · May 22, 2014 at 02:10 PM
You can use linq and SequenceEqual extension to compare the order of two Lists.
using System.Linq;
// Other usings/class declaration, methods, fields.....
// ...
// ...
bool CompareGems()
{
return gems.SequenceEqual(gems1); // SequenceEqual extention returns boolean or true/false.
}
@ Landern i tried to use it as
public void WinOrLose( )
{
if (gems.SequenceEqual (gems1)) {
Application.LoadLevel ("level02");
} else {
print ("try again");
}
}
i call this function and a swap funtion on button click.but whenever i click on button it load level02