使用Array作为Comparer在LINQ查询中覆盖默认排序

时间:2012-02-21 17:24:08

标签: c# linq

我有一个ID号列表,我从会话变量中提取并转换为一个数组,用于LINQ查询,然后用于填充下拉列表。这基本上是程序访问过的最近客户的列表。我希望它按照上次访问的顺序显示它们。

示例数组值(66,78,55,24,80)

在LINQ查询之后,它默认按ID排序:(24,55,66,78,80)

因此,当它显示在下拉列表中时,它按照这种方式排序,当我真正需要的是它保持数组值的顺序时,只反转:(80,24,55,78,66)

代码:

// Grab pre-built session variable with comma delimited int values
string RecentClients = Session["RecentClients"].ToString();

// Convert to Array
int[] RecentClientsArray = 
Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n));

// Display in gridview to see current order of array (For debug purposes)
gridArray.DataSource = RecentClientsArray;
gridArray.DataBind();

// Setup LINQ
DataClasses1DataContext db = new DataClasses1DataContext();

// Populate RecenClientList using RecentClientsArray to compare to ConsumerID
var RecentClientList = 
(from c in db.ClientNames
 where RecentClientsArray.Contains(c.ConsumerID)
 select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID, 
              recentConsumerID = c.ConsumerID});


// Display in gridview to see new order after populating var RecentClientList 
// (for debug purposes)
gridList.DataSource = RecentClientList;
gridList.DataBind();

// Set and bind values for dropdown list.
ddLastClients.DataSource = RecentClientList;
ddLastClients.DataTextField = "FullName";
ddLastClients.DataValueField = "recentConsumerID";
ddLastClients.DataBind();

使用已接受的解决方案修改代码:

// Grab pre-built session variable with comma delimited int values
string RecentClients = Session["RecentClients"].ToString();

// Convert to Array
int[] RecentClientsArray = Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n));

// Setup LINQ
DataClasses1DataContext db = new DataClasses1DataContext();

// Populate RecenClientList using RecentClientsArray to compare to ConsumerID
var RecentClientList = (from c in db.ClientNames
                        where RecentClientsArray.Contains(c.ConsumerID)
                        select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID, recentConsumerID = c.ConsumerID });

var clients = (from item in RecentClientsArray
                join client in RecentClientList.ToList()
                on item equals client.recentConsumerID
                select client).Reverse().Distinct();

// Set and bind values for dropdown list.
ddLastClients.DataSource = clients;
ddLastClients.DataTextField = "FullName";
ddLastClients.DataValueField = "recentConsumerID";
ddLastClients.DataBind();

4 个答案:

答案 0 :(得分:1)

我会在您编写之后留下您的查询,然后处理内存中的排序。

鉴于

var RecentClientsArray = ...
var RecentClientList = ...

您可以使用Enumerable.Join将这些内容整合在一起。 Join具有在连接操作中保留外部序列的顺序的属性。使用联接获取基于数组的初始订单,然后使用Reverse来满足您的最终要求。所以你可能只是

var clients = 
    (from item in RecentClientsArray 
     join client in RecentClientList.ToList() // materialize result from db
     on item equals client.recentConsumerID
     select client).Reverse();

您应该按照数组的相反顺序看到clients,然后将其用作控件上的数据源。

答案 1 :(得分:0)

我认为你需要使用OrderBy(Func<>,IComparer<>)并指定你自己的Comparer来实现你的(直接从stackoverflow复制,对不起)...没有优雅的解决方案实施,然后

答案 2 :(得分:0)

尝试下面的内容,我使用List<int>,因为我需要访问IndexOf,我在LINQ查询的添加的orderby子句中使用它:

       List<int> RecentClientsArray = Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n)).ToList();
       // other code
       var RecentClientList = (from c in db.ClientNames
                               where RecentClientsArray.Contains(c.ConsumerID)
                               orderby RecentClientsArray.IndexOf(c.ConsumerID) descending
                               select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID, recentConsumerID = c.HorizonID });

答案 3 :(得分:0)

我的解决方案:使用带有反向数组项的字典。

这是我的代码:

            // Grab pre-built session variable with comma delimited int values
            string RecentClients = Session["RecentClients"].ToString();

            // Convert to Array
            int[] RecentClientsArray = Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n));


            //NEW- I use dictionary to get the right place in reverse
            int ind = 0;
            Dictionary<int, int> dic = new Dictionary<int, int>();
            foreach (var item in RecentClientsArray.Reverse())
            {
                dic.Add(item, ind);
                ind++;
            }


            // Display in gridview to see current order of array (For debug purposes)
            gridArray.DataSource = RecentClientsArray;
            gridArray.DataBind();

            // Setup LINQ
            DataClasses1DataContext db = new DataClasses1DataContext();

            // Populate RecenClientList using RecentClientsArray to compare to ConsumerID
            //NEW- use orderby with dictionary
            var RecentClientList = (from c in db.ClientNames
            where RecentClientsArray.Contains(c.ConsumerID)
            orderby dic[c.ConsumerID]
            select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID, recentConsumerID = c.HorizonID, ID = c.ConsumerID });

            // Display in gridview to see new order after populating var RecentClientList (for debug purposes)
            gridList.DataSource = RecentClientList;
            gridList.DataBind();

            // Set and bind values for dropdown list.
            ddLastClients.DataSource = RecentClientList;
            ddLastClients.DataTextField = "FullName";
            ddLastClients.DataValueField = "recentConsumerID";
            ddLastClients.DataBind();           



祝你好运,