Using a LINQ Where query to get only some of the ConfigurationManager.ConnectionStrings

此生再无相见时 提交于 2019-12-05 04:28:32
Jeroen

TL;DR Version

You need to do a .Cast<ConnectionStringSettings>() to make this work.

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 is tells you:

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

Driving up the inheritance tree of the ConnectionStringSettings property you can finally see the culprit, which makes a lot of sense: that property is of the non generic IEnumerable type.

This in fact makes the question a rather elaborate duplicate of this question, as the solution lies in casting the non-generic property to a generic list, so that LINQ and the compiler may do their magic. For this particular scenario, the following does work:

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

Enjoy!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!