Using LINQ Where Query to Get Only Some of ConfigurationManager.ConnectionStrings

My goal is to use the LINQ Where query in the ConfigurationManager.ConnectionStrings collection in the console application (suppose the new .NET 4.5 console application with the addition of the System.Configuration reference and the using statement).

I started with this one , which does not work :

 var relevantSettings = ConfigurationManager.ConnectionStrings.Where(s => s.Name.StartsWith("Xyz")); 

This tells me that:

Type arguments for the method ' IEnumerable<TSource> System.Linq.Enumerable.Where<TSource(this IEnumerable<TSource>, Func<TSource,bool>) ' cannot be taken out of use. Try explicitly specifying arguments.

It caught me on my guard, so I tried this to check my sanity, but it does not work :

 foreach (var settingsin ConfigurationManager.ConnectionStrings) { if (settings.Name.StartsWith("Xyz")) Console.WriteLine("Found one!"); } 

He complains not about the foreach , but about the .Name bit with an error:

Failed to resolve name character

I understand that maybe something is stopping the compiler from inferring the var type to double check that I tried this one that works :

 foreach (ConnectionStringSettings settings in ConfigurationManager.ConnectionStrings) { if (connectionString.Name.StartsWith("Xyz")) Console.WriteLine("Found one!"); } 

However, this does not help me much, except to solve my immediate problem. I want to understand what is happening here.

All I wanted to do was use the simple LINQ Where statement to get a subset of the connection strings in my app.config. Why is the compiler stopping me from doing this?

+5
source share
1 answer

TL DR version

To do this, you need to do .Cast<ConnectionStringSettings>() .

More details

Well, if you dig even a little deeper, you can get the compiler to tell you even more:

 Func<ConnectionStringSettings, bool> StartsWithXyz = c => c.Name.StartsWith("Xyz"); var relevantSettings = ConfigurationManager.ConnectionStrings.Where(StartsWithXyz); 

This tells you:

Cannot convert instance argument type ' System.Configuration.ConnectionStringSettingsCollection ' to ' System.Collections.Generic.IEnumerable<System.Configuration.ConnectionStringSettings> '

Driving the inheritance tree of the ConnectionStringSettings property, you can finally see the culprit, which makes a lot of sense: this property is not of the general IEnumerable type .

This actually makes the question a pretty thoughtful duplicate of this question , since the solution is to distinguish a non-generic property from a universal list, so LINQ and the compiler can do their magic. For this particular scenario , the following works :

 var relevantSettings = ConfigurationManager.ConnectionStrings .Cast<ConnectionStringSettings>() .Where(c => c.Name.StartsWith("Xyz")); 

Enjoy it!

+13
source

Source: https://habr.com/ru/post/1204900/


All Articles