hi im rather new to unity and c# im trying to sort a list of custom objects by a specific value, which works fine, but now i want to check if the value is the same and if it is sort the two objects by another value so for instance if all objects have int A and int B i want to sort the list by int A but if object 1 int A is the same as object 2 int A then sort these 2 objects by int B aswell, but only for these matching objects not the rest of the list (unless there is another tie) im sure there will be a built in function in list.sort to deal with this i just havent been able to find it, many thanks
You would need to use something like this:
public class Vector : IComparer<Vector>
{
int A, B;
public Vector (int a, int b)
{
A = a;
B = b;
}
int IComparer<Vector>.Compare (Vector a, Vector b)
{
return (a.A == b.A) ? ((a.B == b.B) ? 0 : ((a.B > b.B) ? 1 : -1)) : ((a.A > b.A) ? 1 : -1);
}
}
I called this class Vector (because it is basically a Vector2). You implement an IComparer interface which tells the list how you sort this custom class - in the custom class, I used a huge ternary return value because, well, I think it’s elegant, if you don’t understand it just comment this and I’ll give you the if-else variant. I also assume that you want the comparer to have an equal value if both the A and B are the same, I’ve included that.
i actually found a much more descriptive answer here C# IComparable Example - Dot Net Perls ive added an IComparable to my object class making it look like this
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public class fighterObject : IComparable<fighterObject>
{
public int Universe { get; set; }
public int KillCount { get; set; }
public int JointKillCount { get; set; }
public string Name { get; set; }
public string Info { get; set; }
public string JointKillInfo { get; set; }
public Sprite Image { get; set; }
public fighterObject(int universe,
int killcount,
int jointkillcount,
string name,
string info,
string jointKillInfo,
Sprite image )
{
Universe = universe;
KillCount = killcount;
JointKillCount = jointkillcount;
Name = name;
Info = info;
JointKillInfo = jointKillInfo;
Image = image;
}
public int CompareTo(fighterObject other)
{
// Alphabetic sort if salary is equal. [A to Z]
/*
if (this.KillCount == other.KillCount && this.JointKillCount == other.JointKillCount)
{
return this.Name.CompareTo(other.Name);
}
*/
if (this.KillCount == other.KillCount)
{
return other.JointKillCount.CompareTo(this.JointKillCount);
}
// Default to salary sort. [High to low]
return other.KillCount.CompareTo(this.KillCount);
}
public override string ToString()
{
// String representation.
return this.KillCount.ToString() + " , " + this.JointKillCount.ToString() + " , " + this.Name;
}
}
which allows me to just call list.sort() on any list containing fighterObject