Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'orderby' in linq using a string array c#

Tags:

c#

linq

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

like image 849
ltech Avatar asked Dec 05 '22 03:12

ltech


1 Answers

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();
like image 108
tvanfosson Avatar answered Dec 08 '22 10:12

tvanfosson