'orderby'在linq中使用字符串数组c# [英] 'orderby' in linq using a string array c#

查看:604
本文介绍了'orderby'在linq中使用字符串数组c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个方法定义为这样的:

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



我的输入参数CustomerIDs可能是{1,3, 400,200}

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?

我的解决办法是把它变成一个字典,然后创建一个新的数组,而通过我的CustomerIDs收集循环。

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

CustomerOrderData确实有一个名为客户ID属性

CustomerOrderData does have a property named CustomerID

推荐答案

如果您兑现了查询,应该能够找到的ID的索引阵列中,并用它作为排序参数。 。下面显示的使用扩展方法

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

这篇关于'orderby'在linq中使用字符串数组c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆