Reputation: 2750
I have list 'companies' from database.
And then I have another dictionary like:
Dictionary<int, string> ordering = new Dictionary<int, string>();
ordering.Add(1, "VIP");
ordering.Add(2, "VIP+");
ordering.Add(3, "Regular");
The companies list has to be ordered by this Dictionary.
How can I do that?
I can't join 'companies' with dictionary 'ordering', if I do I get an exception.
Is there any way to 'order by' by this 'ordering' key .
The dictionary values(vip, vip+,regular) corresponds with a column in my companies list.
Upvotes: 1
Views: 166
Reputation: 6299
You can use a custom OrderBy statement like:
public List<Company> OrderCompanies()
{
Dictionary<int, string> ordering = new Dictionary<int, string>();
ordering.Add(1, "VIP");
ordering.Add(2, "VIP+");
ordering.Add(3, "Regular");
// This could be the database source
List<Company> companies = new List<Company>();
companies.Add(new Company() { CompanyCategory = "VIP" });
companies.Add(new Company() { CompanyCategory = "VIP+" });
return companies
.OrderBy(company => ordering.First(pair => pair.Value == company.CompanyCategory).Key)
.ToList();
}
Upvotes: 0
Reputation: 2113
In addition to what Jon G said, you can also do it with a join. Something like this should do the trick:
var companyQuery = from c in companies
join kvp in ordering on c.CompanyCategory equals kvp.Value
orderby kvp.Key
select c;
Upvotes: 0
Reputation: 4164
It looks as though your ordering dictionary is back-to-front with respect to the way you need to use it, which is to look up based on a text key and give a numeric ordering. I would recommend 'inverting' your ordering dictionary first, then you can sort the companies for the cost of a dictionary lookup per entry, plus the cost of the LINQ sorting algorithm.
var swappedOrdering = ordering.ToDictionary(kvp => k.Value, kvp => k.Key);
var orderedCompanies = companies.OrderBy(c => ordering[c.CompanyCategory]);
Keep in mind though that your ordering dictionary is memory, not in the database, so in order to use this approach you would need to spool all the records back into memory. If you want the database to do the hard work, you'll have to put this ordering information into the database.
Upvotes: 1