1

I have LINQ result, and I have List. I want to do Where() on the LINQ and to REMOVE all the matching strings from the List.

I get errors of: Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator

What can I do?

1
  • 2
    please post a full code sample. Commented Nov 22, 2010 at 15:34

2 Answers 2

3

You need to call AsEnumerable() or ToList() before your Where call to force LINQ-to-SQL to download all results to the client and perform a local Where.

(Since your Where call cannot be performed on the server, you need to do it on the client)

Sign up to request clarification or add additional context in comments.

6 Comments

Does AsEnumerable always force materialisation?
Because it's effectively just a cast: msdn.microsoft.com/en-us/library/bb335435.aspx "The AsEnumerable<TSource>(IEnumerable<TSource>) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable<T> to IEnumerable<T> itself."
@Rob: But it prevents you from calling IQueryable methods. Calling Enumerable LINQ methods will force materialization.
Compare List<int> ints = new List<int>{1,2,3,4}; var evens = ints.Where(x => x%2==0).AsEnumerable(); foreach(int i in evens){ ints.Remove(i); } with List<int> ints = new List<int> 1,2,3,4}; var evens = ints.Where(x => x%2==0).ToList(); foreach(int i in evens){ ints.Remove(i); } (Sorry about the formatting)
@Rob: What does that have to do with anything?
|
2

You need to make a copy (with ToList, which is faster than ToArray) of the items you're removing:

var removeMe = list.Where(...).ToList();

Now removeMe wil be safe to iterate through, however, a better approach would be to use the List.RemoveAll method, because then you don't need any temporary data structures

2 Comments

Unless your set has exactly 2^N items, ToArray will need to copy to a smaller array after it finishes (since the array must be exactly the right size). Since lists can have extra space at the end, ToList will involve fewer copies.
.Where().ToList() will be faster than .ToList().RemoveAll(), since it won't need to shift the items in the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.