3

In my application, I have Property Setting which is of type String.Collections.Specialized.StringCollection. It contains a list of customer codes such as MSFT, SOF, IBM etc. I'm trying to use this in a Linq-to-Entities query in the where clause:

var ShippedOrders = dbcontext.Orders
 .Where(s=>(s.Status.Description.Equals("Shipped") && !Properties.Settings.Default.CustomersToExclude.Contains(s.CustomerCode)));

This fails as Contains is not recognized by Linq-to-Entities with a message similar to:

"LINQ-to-Entities does not recognize the method Contains...."

How do I revise the code above to avoid this error?

FMFF
  • 1,652
  • 4
  • 32
  • 62

3 Answers3

16

A shorter path is

myProperties.Settings.Default.CustomersToExclude.Cast<string>().Contains(blah); 

That's a handy trick for any situation where a collection isn't inherently LINQ-aware.

Snort Kapp
  • 161
  • 1
  • 3
2

Since your question is tagged as C# 4 use a List<string> instead (StringCollection is ancient) and your query should work. Also you should resolve your list reference outside your query:

List<string> customersToExclude = ..
var ShippedOrders = dbcontext.Orders
                             .Where(s=>(s.Status.Description.Equals("Shipped") 
                                    && !customersToExclude.Contains(s.CustomerCode)));

Edit:

Just copy your customers to an array and use that:

var customerstoExclude = new string[Properties.Settings.Default.CustomersToExclude.Count];
myProperties.Settings.Default.CustomersToExclude.CopyTo(customerstoExclude, 0);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • But List is not an option in the Type drop down in Project Properties -> Settings. That is where I get my list to exclude from. – FMFF Feb 08 '12 at 17:32
  • 1
    @FMFF: You could just copy to a string array in that case, see update – BrokenGlass Feb 08 '12 at 17:38
1

This is answered in a related question. EF4 apparently supports Contains directly, though, so that'd be my prefered solution... :)

Community
  • 1
  • 1
Jacob Proffitt
  • 12,664
  • 3
  • 41
  • 47