开发者

'orderby' in linq using a string array c#

开发者 https://www.devze.com 2022-12-20 06:21 出处:网络
Say I have a method definition as such: public CustomerOrderData[] GetCustomerOrderData(string[] CustomerIDs)

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


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();


I think this solves problem:

var orderedArray = YourCustomArray.OrderBy(s => s).ToArray();


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);


You could use IndexOf:

orderby ContactIds.IndexOf(a.CustomerId)

Note that this might not be efficient for large sets.


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]  
    ...


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号