Everyone_Else
Everyone_Else

Reputation: 3264

Sort any one of a few arbitrary classes that all contain a certain parameter

I have a lot of classes that are all certain to contain an int called val, which I'd like to sort them on. They look something like this:

public class KeyString
{
    public string key;
    public int val;
}
public class KeySprite
{
    public Sprite key;
    public int val;
}
public class KeyInt
{
    public int key;
    public int val;
}

Currently I sort them like this:

public static List<KeyString> SortKeyString(List<KeyString> l){
        l.Sort((a,b) => a.val.CompareTo(b.val));
        return l;
    }
public static List<KeySprite> SortKeySprite(List<KeySprite> l){
        l.Sort((a,b) => a.val.CompareTo(b.val));
        return l;
    }
public static List<KeyInt> SortKeyInt(List<KeyInt> l){
        l.Sort((a,b) => a.val.CompareTo(b.val));
        return l;
    }

This ... works, in the sense that it gets the right answer, but to me this feels like potentially unnecessary code duplication. Is it possible to write a single sort method that could sort a list of any of these classes?

(Note: I'm only sorting lists of a single class at a time - We're not trying to combine two different classes here.)

Upvotes: 1

Views: 28

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

Create a class like:

public class KeyBase
{
    public int val;
}

now Inherit all your classes from it:

public class KeyString : KeyBase
{
    public string key;
}
public class KeySprite : KeyBase
{
    public Sprite key;
}
public class KeyInt : KeyBase
{
    public int key;
}

public static List<T> SortKey<T>(List<T> l) where T: KeyBase
{
    l.Sort((a,b) => a.val.CompareTo(b.val));
    return l;
}

If the only different in your classes is the type of key variable, you can do something like:

public class Key<T>
{
    public T key;
    public int val;
}

public static List<Key<T>> Sort<T>(List<Key<T>> l)
{
        l.Sort((a,b) => a.val.CompareTo(b.val));
        return l;
}

var stringKeys = new List<Key<string>> { ... };
var intKeys = new List<Key<int>> { ... };
var SpriteKeys = new List<Key<Sprite>> { ... };

Demo

Upvotes: 1

Related Questions