2009-12-30 100 views
0

我有以下LINQ查询:用IN运算符LINQ to SQL动态排序?

using (var db = new MyDataContext()) { 
    int[] onlineUsers = GetOnline(); 
    var users = (from u in db.Users orderby 
     (onlineUsers.Contains(u.u_username) && 
     u.u_hasvisible_photo) descending, 
     u.u_lastlogin descending select 
     u.u_username).Skip(startRowIndex). 
     Take(maximumRows).ToList(); 
} 

这工作得很好,并产生使用IN操作符的SQL查询。

问题是int []中的每个int都通过一个不同的参数传递,我知道每个查询SQL有2100个参数的限制。

我认为使用LINQ动态库OrderBy来做排序会更好。

而不是“onlineUsers.Contains(u.u_username)& & u.u_hasvisible_photo)descending”use.OrderBy(orderquery)。

我已经在网上搜索指导或示例来做到这一点,并找不到任何help.Could社区可以帮助我的代码或链接,可以帮助我实现这一点?

回答

0

如果您使用的是SQL Server 2008,则可以创建一个标量函数,该函数需要table-valued parameter,然后像这样传递数组。虽然(你没有指定你正在使用哪一个(Linq-to-Entities或Linq-to-SQL,而且我假定SQL Server,即使你只是说“sql” ),所以我不确定如何组合查询将

你可能想要做的是创建一个table valued user-defined function它采用表值参数(和任何其他参数,你可能有),并通过LINQ公开(你应该能够创建一个从表值函数的东西可组合),然后从那里出发。

0

下面是的LINQ to SQL一个例子,它允许您订购动态。这个例子是使用罗斯文数据库,你可以简单地尝试一下与LinqPad

void Main() 
{ 

    // Demonstrates dynamic ordering 

    var SortExpression = "Total"; // choose ProductName or Total 
    var sortAscending = true; // choose true for ascending, false for descending 

    // the query to sort 
    var data = (from pd in Products 
         join od in OrderDetails on pd.ProductID equals od.ProductID into DetailsByProduct 
         select new { ProductName = pd.ProductName, Total = DetailsByProduct.Count()}).ToList(); 

    // the data source you can use for data binding      
    var ds= (sortAscending) 
     ? data.OrderBy(x => x.GetType().GetProperty(SortExpression).GetValue(x, null)) 
     : data.OrderByDescending(x => x.GetType().GetProperty(SortExpression).GetValue(x, null)); 

    ds.Dump(); 
} 

尝试通过"ProductName"(可变SortExpression)取代"Total",或作为排序依据使用false(可变sortAscending)下降。