I'm trying to use LINQ in a C# (Polyglot Notebook).
using System.Linq;
Environment.GetEnvironmentVariables().Values.Select(x => x)
But I'm getting the error:
Error: (3,46): error CS1061: 'ICollection' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?)
CodePudding user response:
You don't need the using statement, LINQ should be available/imported by default. The "issue" here is that Environment.GetEnvironmentVariables()
returns a non-generic IDictionary
and it's Values
property is non-generic ICollection
(which implements non-generic IEnumerable
) which does not support much of LINQ's methods besides Cast
, most of LINQ works with generic version of IEnumerable
. So you can use Cast
or OfType
:
Environment.GetEnvironmentVariables().Values
.Cast<string>() // or `OfType<string>()`
.Select(i => i);
CodePudding user response:
var result = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
.Select(x => x.Value).ToList();