tags:

views:

161

answers:

5

Say I have a method definition as such:

public CustomerOrderData[] GetCustomerOrderData(string[] CustomerIDs)
{
 var query = (from a in db.Customer
              join b in db.Order on a.CustomerID equals v.CustomerID
              orderby CustomerIDs
              select new CustomerOrderData()
              {
                //populate props here
              }).ToArray();
}

My CustomerIDs in input param could be {"1","3","400","200"}

I want my return array to be ordered in the above fashion. Is there an easy way to achive this?

My solution was to put it into a Dictionary and then create a new array while looping through my CustomerIDs collection.

CustomerOrderData does have a property named CustomerID

A: 

You could use IndexOf:

orerby ContactIds.IndexOf(a.CustomerId)

Note that this might not be so efficient for large sets.

SLaks
A: 

if the customerIds always will be numbers then cast it and order it before using it into ur query

var orderedIds =  CustomerIDs.Cast<int>().OrderBy(x => x);
Amgad Fahmi
+3  A: 

If you materialize the query, you should be able to find the index of the id in your array and use it as the ordering parameter. Shown below using extension methods.

var ordering = CustomerIDs.ToList();
var query = db.Customer.Join( db.Order, (a,b) => a.CustomerID == b.CustomerID )
                       .AsEnumerable()
                       .OrderBy( j => ordering.IndexOf( j.Customer.CustomerID ) )
                       .Select( j => new CustomerOrderData {
                          // do selection
                        })
                       .ToArray();
tvanfosson
tvanfosson: I tried your method, the returned array does not appear to be sroted by my CustomerIDs string[]. Seems that data is sorted in descending order
ltech
Is customerID a string in the entity class? If not, try doing an IndexOf( j.Customer.CustomerID.ToString() ) -- or change your array to an array of int values (assuming that's the type on the entity).
tvanfosson
A: 

You could create a structure to lookup the desired index using the customerid.

string[] CustomerIDs;

Dictionary<string, int> customerIDOrdering = CustomerIds
  .Select((c, i) => new (id = c.CustomerID, i = i})
  .ToDictionary(x => x.id, x => x.i);

var query = from c in ...
    orderby customerIDOrdering[c.CustomerID]  
    ...
David B
A: 

The join clause preserves the order of the outer sequence:

"The Join operator preserves the order of the outer sequence elements, and for each outer element, the order of the matching inner sequence elements."

http://msdn.microsoft.com/en-us/library/bb394939.aspx

So you should not need to orderby at all:

from orderIndex in CustomerIDs
join a in db.Customer on orderIndex equals a.CustomerID
join b in db.Order on a.CustomerID equals v.CustomerID
uosɐſ