Reputation: 383
I have a bog-standard list in C#: List (where Channel is a TV channel). Channel is defined as:
public class Channel
{
public int ChannelId { get; set; }
public string ChannelName { get; set; }
}
My ORM populates a list of Channels, which comes from the database in Channel Id order. I need to re-order the list based on a new custom sort property, say ChannelOrder, but I can't modify the underlying database.
Any thoughts on how to do this, without modifying the underlying DB?
So for instance, if I current have coming from the db:
ChannelId =1, ChannelName = "BBC1", ChannelId =2, ChannelName = "BBC2", ChannelId =3, ChannelName = "ITV"
I might want them ordered as BBC2, BBC1, ITV, basically a custom order.
Upvotes: 0
Views: 141
Reputation: 22794
You could maybe use another class that returns an "attached" property, kind of like attached properties in WPF:
public static class ChannelSort
{
static Dictionary<Channel, int> _dict = new Dictionary<Channel, int>();
public static int GetSort(this Channel c)
{
return _dict[c] //will throw if key's not found,
//may want to handle it for more descriptive exception
}
public static int SetSort(this Channel c, int sort)
{
_dict[c] = sort;
}
}
And then you could do this:
var result = unsortedList.OrderBy(c => c.GetSort());
Upvotes: 0
Reputation: 1499840
If you're happy to do this in-process (rather than as part of the query) you can use:
var orderedChannelNames = new[] { "BBC2", "BBC1", "ITV", ... };
var sorted = unsorted.OrderBy(ch => orderedChannelNames.IndexOf(ch.ChannelName));
Alternatively, if you know all the channels in your list will be present:
var map = unsorted.ToDictionary(ch => ch.ChannelName);
var sorted = orderedChannelNames.Select(name => map[name]);
Upvotes: 2