2013-10-30 48 views
2

与LINQ运营商很多时候我都需要类似这样的疑问:SQL 'IN' 在Visual Studio LightSwitch中

SELECT * FROM Customers 
WHERE City IN ('Paris','London'); 

我有一些列表(最常见的字符串)。当列表很小(如本例中),它是没有这样的问题,我可以写这样的事情(C#):

Customers custs = this.DataWorkspace.ApplicationData.Customers; 
var filteredcustomers = custs.Where(c=>c.City == "Paris" || c=>c.City == "London"); 

但如果我有更大的名单,这是一个有点笨拙。 我已经试过这(从一些论坛):

List<string> months = new List<string>() {"Jan", "Feb", "Mar"......"Dec"}; 
Customers custs = this.DataWorkspace.ApplicationData.Customers; 
var filteredcustomers = custs.Where(c => months.Contains(c.City)); 

,但我得到运行时错误:
“{System.NotSupportedException: 表达式的值(System.Collections.Generic.List`1 [ 。System.String])包含([10007]。城市),不支持......”

回答

0

试试这个:

var filteredCustomers = from fcusts in custs where custs.Any(x=>x.Contains<string>(x.City)) select fcusts; 

这种方式,您将调用Enumerable.Contains并没有列出。包含。

0

使用数组而不是List <>

var filteredcustomers = custs.Where(c => months.ToArray().Contains(c.City)); 
1

首先,感谢双方@danielrozo和回答问题@ sh1ng。 问题是,这两个建议在运行时不起作用,当我在代码的某个时候尝试执行.Execute()查询或执行foreach循环(当查询实际执行时),并且我认为我终于明白为什么:

this.DataWorkspace.ApplicationData.Customers; 

这是EntitySet,我发现它不支持全套LINQ运算符(它不支持'Contains')。它仅支持受限制的LINQ运算符。如果列表例如:

List<string> cities = new List<string>() {"Paris", "London", "Berlin", "Moscow",.....}; 

,我修改“custs”是这样的:

var custs = this.DataWorkspace.ApplicationData.Customers.GetQuery().Execute(); 

它返回IEnumerable的对象,我们可以用它来过滤本地。 IEnumerable支持全套LINQ操作符,现在两种建议都可以使用。例如。从@danielrozo

var fi = from fcusts in custs where custs.Any(x => cities.Contains(x.City)) select fcusts; 

现在,这也适用:

var filteredcustomers = custs.Where(c => cities.Contains(c.City)); 

而且(需要时)我可以做算术:

decimal total = custs.Where(c => cities.Contains(c.City)).Sum(c => c.Points); 

我们需要小心的是,因为.GetQuery ().Execute()返回来自服务器(本例中为客户)的所有记录,如果我们有很多记录,这可能会影响性能。

我希望这会帮助别人。

相关问题