There are some entities in the application I'm developing that need to be sorted by a predefined routine.
Thinking about this has created a contract class called ElementoOrdenavel
and all entities that can be ordered inherit from this class.
It exposes, a priori , only two members. Here is the class code.
public abstract class ElementoOrdenavel
{
public int Id { get; set; }
public int Ordem { get; set; }
}
Example of a class that inherits from this
public class Banner : ElementoOrdenavel
{
public string Descricao { get; set; }
}
To facilitate my work, I've made a method that gets a list of ElementoOrdenavel
and does the sorting work, so
void Reorganizar(IEnumerable<ElementoOrdenavel> colecao, int[] idsOrdenados)
{
for (int ordem = 0; ordem < idsOrdenados.Length; ordem++)
{
var elemento = colecao.First(m => m.Id == idsOrdenados[ordem]);
elemento.Ordem = ordem + 1;
}
}
And I tried calling this method as well
var banners = db.Banners.AsEnumerable();
Reorganizar(banners, ids);
And, to my surprise, I received the error
Can not convert from '
IEnumerable<Banner>
' to 'IEnumerable<ElementoOrdenavel>
'
A list of Banner
not is a list of ElementoOrdenavel
?
By doing a generic method, it works normally. Because?
void Reorganizar<T>(IEnumerable<T> colecao, int[] idsOrdenados) where T : ElementoOrdenavel
{
for (int ordem = 0; ordem < idsOrdenados.Length; ordem++)
{
var elemento = colecao.First(m => m.Id == idsOrdenados[ordem]);
elemento.Ordem = ordem + 1;
}
}