I've got two classes which has two common properties Id
and SortNumber
. I wanted to have a generic method to sort items in a list of said classes.
Is it possible to not implement the interface IOrderitem
to classes Foo
and Bar
but still be able to use the method MoveUp
?
Or is reflection the only alternative? Been writing mostly TypeScript code last few years so a bit rusty on C#.
public class Foo
{
public int Id {get;set;}
public int SortNumber {get;set;}
// etc
}
public class Bar
{
public int Id {get;set;}
public int SortNumber {get;set;}
// etc
}
public interface IOrderitem
{
int Id {get;set;}
int SortNumber {get;set;}
}
public static void MoveUp<T>(List<T> itemList, int id)
{
for (int i = 0; i < itemList.Count; i++)
{
// reindex items
var item = itemList[i] as IOrderItem;
bool isItem = item.Id == id;
if (isItem && i > 0)
{
// set item above eventinfo item to one position lower (0 = top rest lower)
(itemList[i - 1] as IOrderItem).SortNumber = i;
// set the item to move up one position higher (0 = top rest lower)
item.SortNumber = i - 1;
i++;
}
else
{
item.SortNumber = i;
}
}
}