In LINQ, the expression after key word "select" cannot get local varible before it #4937
-
I have a piece of code like this.
orginally, I wanted to write like this:
However it gave me Compiler Error CS0103, The name 't' does not exist in the current context. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Beta Was this translation helpful? Give feedback.
-
Unfortunately the team rejected and effectively closed the door to allowing LINQ queries to behave as you suggest. The pattern variables declared within a LINQ clause are not promoted to range variables and not available through the rest of the query. There was a proposal at one point to allow pattern variables declared within the from item in collection
let isT = item is T value
where isT
select value But it seems that was never implemented and that probably couldn't be implemented without source breaking changes (albeit very minor ones). Right now the best you can do is: from item in collection
let match = item is T value ? (true, value) : (false, default)
where match.Item1
select match.Item2; |
Beta Was this translation helpful? Give feedback.
-
In the spirit of trying to get you through your current use cases... don't forget about the In the example you gave you'd use it like this: public static IEnumerable<T> FindInCircle<T>(this GameWorld gameWorld, Vector2 center, double range)
where T : GameBody
{
return gameWorld.world.CircleHitTest(center, range).OfType<T>();
} |
Beta Was this translation helpful? Give feedback.
In the spirit of trying to get you through your current use cases... don't forget about the
.OfType<>()
Linq method.In the example you gave you'd use it like this: