perene
perene

Reputation: 421

Prevent new values from LINQ query

I have some data in a List I want to make a query against. In the meantime however, other users can add to this List and I get wrong items in return:

var query = from s in selected
            where s.contains("www")
            select s);

Then a user Can add item to selected list before The query is run, and I Will get this also. Can I prevent this behaviour?:

selected.add("123www")

foreach (var s in query)
/// gives me 123www

Upvotes: 2

Views: 96

Answers (3)

Thomas
Thomas

Reputation: 1563

The var "query" just has the query assigned to it, but the query itself is first performed when the query is accessed in for example a foreach loop - hence you get the newly added data.

If you don't want this, you can use an extension method like "ToList()", where the collection stays the same:

var queryResultList = (from s in selected
             where n.contains("www")
             select s).ToList();

Here the ToList() iterates the collection immediately, and you can now iterate the queryResultList and get the right results and even though new elements arrive the output stays the same.

Upvotes: 7

JiBéDoublevé
JiBéDoublevé

Reputation: 4269

When you call .ToList() or .ToArray() the query is executed. Therefore to avoid your problem you can write this code:

var query = from s in selected
            where s.Contains("www")
            select s);

var result = query.ToList();
selected.Add("123www");

foreach(var item in result)
{
     /* You won't see "123www" */
}

Upvotes: 0

Eduard Dumitru
Eduard Dumitru

Reputation: 3252

The query represents an action, which can be triggered any time you want and it will yield different results if the source of data changed.

Just make a "snapshot" of the results at the time you desire to do so with a .ToArray():

var query = from s in selected
                Where s.contains("www")
                Select s)
string[] snapshot = query.ToArray();

Upvotes: 0

Related Questions