I have below table for categories.
tbCategories
CatgID CatgName
------ --------
1 Catg1
2 Catg2
3 Catg3
4 Catg4
Now I have items table which is categorized linking to above categories
tbItem
ItemID ItemName ItemCatg Priority
------ -------- -------- --------
1 Name 1 1 1
2 Name 2 1 2
3 Name 3 2 1
4 Name 4 3 3
5 Name 5 4 2
6 Name 6 3 1
Priority
1 - High
2 - Medium
3 - Low
Now when I display the item data, I want the to first display items with category Catg1, Catg2 and Catg4 based on their priority, then display items with Catg3 based on their priority.
I had tried below LINQ expression, but I did not succeed with that. My knowledge on LINQ or SQL is not too strong but that's how much I could reach.
model.items = db.tbItem.OrderBy(p=>p.ItemCatg).ThenBy(p=>p.Priority).ToList();
Could someone please show me the right way to achieve this functionality?
UPDATE
I would like to achieve below combination while displaying.
ItemID ItemName ItemCatg Priority
------ -------- -------- --------
1 Name 1 1 1
3 Name 3 2 1
2 Name 2 1 2
5 Name 5 4 2
6 Name 6 3 1
4 Name 4 3 3
The following is a trick I've used in the past. You're basically relying on the result of the comparison ordering things first by the non-3 categories (i.e., the false equates to 0, the true to 1) then by the priority, then by the category.
tbItems.OrderBy(p=>p.ItemCatg == 3).ThenBy(p=>p.Priority).ThenBy(p=>p.ItemCatg).ToList();
Here's a .NET Fiddle example.
Here's the output from the example:
ItemID: 1 ItemName: Name 1 ItemCatg: 1 Priority: 1
ItemID: 3 ItemName: Name 3 ItemCatg: 2 Priority: 1
ItemID: 2 ItemName: Name 2 ItemCatg: 1 Priority: 2
ItemID: 5 ItemName: Name 5 ItemCatg: 4 Priority: 2
ItemID: 6 ItemName: Name 6 ItemCatg: 3 Priority: 1
ItemID: 4 ItemName: Name 4 ItemCatg: 3 Priority: 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With