OlyDun
OlyDun

Reputation: 33

How to clear the contents of an IEnumerable

Dim sortQuery = From results In resultList
                Order By results.getUsername()
                Where results.getUsername() = passUsername
                Select results.getAll()
For Each Str As String In sortQuery
    lstBox.Items.Add(Str)
Next

I have created a generic IEnumerable of objects. The object class is results, resultList is a list of many instances of that object. In order to carry out multiple queries, I intend to repeat this code but with different conditions.

When this code is repeated, it outputs results for that search in addition to all results from previous searches made. I believe that clearing the IEnumerable between queries will prevent this. Is there a way to do this? Alternatively, how could I make it so that each query outputs only the results for that query and not those for the previous ones as well?

Upvotes: 3

Views: 2880

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

You can't clear an IEnumerable(Of T). That interface just means that you can enumerate a list of items. It says nothing about how those items are stored. In the case of a LINQ query, it's not the items that are stored but information on how to get them from a source list. The list of items that results from executing the query is not stored separately anywhere to clear but is generated by applying the query logic each time.

If you want to execute similar but different queries then you need to create multiple queries. You can create a single base query that contains the common logic and then you can just apply the specific parts to each specific query. For instance, if you wanted to get all the Person objects from a list but you wanted the males and females separately then you could do this:

Dim baseQuery = From person In people
                Where person.FamilyName = "Smith"
Dim maleQuery = From person In baseQuery
                Where person.Sex = Sex.Male
Dim femaleQuery = From person In baseQuery
                  Where person.Sex = Sex.Female

All three of those queries are stored as logic, not as objects. When you enumerate maleQuery or femaleQuery, you are executing that logic and getting the results one by one. In each case, the logic stored in baseQuery is executed as well as the logic in the more specific query so you get both filters applied at the same time.

EDIT: I should clarify and say that you cannot clear an IEnumerable(Of T) via that interface. For instance, a List(Of T) implements the IEnumerable(Of T) interface and you can clear that, but it's that class that provides that functionality. If all you know about an object is that it implements IEnumerable(Of T) then you can't clear it because you have no idea if it has functionality besides that defined by that interface. A LINQ query definitely doesn't have such functionality because there's no actual concrete list to clear.

Upvotes: 5

Related Questions