1

How would I sort this table rows by following order using linq orderby function:

  1. first by Business type == A01 - Production
  2. second by Business type == A06 - External trade without explicit capacity, where In Area == ME, Out Area by alphabet
  3. third by Business type == A06 - External trade without explicit capacity, where Out Area == ME, In Area by alphabet
  4. fourth by Business type == A02 - Internal trade
  5. fifth by Business type == A04 - Consumption

enter image description here

4
  • Is it Linq to Objects, or you are querying database? Commented Oct 29, 2013 at 10:26
  • 1
    You should try something, and also give us the model. What do mean by where In Area == ME, Out Area by alphabet ? Commented Oct 29, 2013 at 10:26
  • @AhmedKRAIEM it means that items with same A06 - External trade without explicit capacity are sorted also by area Commented Oct 29, 2013 at 10:29
  • In Your case for multiple order you should use Orderby(condition).ThenBy(condition); Commented Oct 29, 2013 at 10:30

2 Answers 2

1

Actually it is possible to create single query without unions:

var query = 
   db.Foos
     .OrderBy(f =>
         f.BusinessType == "A01 - Production" ? 0 :
         f.BusinessType == "A06 - External trade without explicit capacity" ?
           (f.InArea == "ME" ? 1 : (f.OutArea == "ME" ? 2 : 6)) :
         f.BusinessType == "A02 - Internal trade" ? 3 :
         f.BusinessType == "A04 - Consumption" ? 4 : 5)
     .ThenBy(f =>
         f.BusinessType == "A06 - External trade without explicit capacity" ?
             (f.InArea == "ME" ? f.OutArea : 
             (f.OutArea == "ME" ? f.InArea : ""))  : "");

If you are using Linq to Objects, then simply provide custom comparer, or override Equals and GetHashCode of your objects.

Sign up to request clarification or add additional context in comments.

Comments

1

I guess that this is what you want to do:

var result = 
  input.Where(e => e.BusinessType == "A01 - Production")
       .Concat(input.Where(e => e.BusinessType == "A06 - External trade without explicit capacity" && e.InArea == "ME")
                    .OrderBy(e => e.OutArea))
       .Concat(input.Where(e => e.BusinessType == "A06 - External trade without explicit capacity" && e.OutArea == "ME")
                    .OrderBy(e => e.InArea))
       .Concat(input.Where(e => e.BusinessType == "A02 - Internal trade"))
       .Concat(input.Where(e => e.BusinessType == "A04 - Consumption"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.