Bob Horn
Bob Horn

Reputation: 34325

Task Does Not Contain a Definition for Where If Done in One Line of Code

Why does this work if I split the code into two lines:

List<Foo> foos = await _repo.GetFoos();
foos = foos.Where(x => x.FooType != FooType.A).ToList();

But doesn't work when I combine them and do the Where on the same line?

List<Foo> foos = await _repo.GetFoos().Where(x => x.FooType != FooType.A).ToList();

This produces an error:

Task<List<Foo>> does not contain a definition for 'Where`...

Upvotes: 2

Views: 1552

Answers (2)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

You should use await like this:

List<Foo> foos = (await _repo.GetFoos()).Where(x => x.FooType != FooType.A).ToList();

That's because .Where() in await _repo.GetFoos().Where() is applied to _repo.GetFoos() not result of await _repo.GetFoos().

Upvotes: 9

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

The await is applied to the object returned by the entire expression.

You are attempting to use Enumerable.Where on the Task returned by _repo.GetFoos which is invalid.

You could enclose the await _repo.GetFoos() in parentheses to force that to be evaluated first, then Enumerable.Where would be performed on the resultant IEnumerable.

Upvotes: 3

Related Questions