Use Linq to iterate over ConfigurationManager.Conn

2019-07-19 14:54发布

Is it possible to do something like this?

var strings = ConfigurationManager.ConnectionStrings;

var names = (from d in strings
             select new ConnectionName(d.Name));

3条回答
smile是对你的礼貌
2楼-- · 2019-07-19 15:03

Yes, but because ConnectionStrings does not implement a strongly typed IEnumerable, you have to tell LINQ what type the collection contains.

Use either from ConnectionStringSettings d in strings or ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>().

查看更多
爷的心禁止访问
3楼-- · 2019-07-19 15:12

You can loop with a foreach:

Just use the conn property you're looking for

foreach (var conn in ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>())
{
    conn.Name
}
查看更多
可以哭但决不认输i
4楼-- · 2019-07-19 15:16

You have to Cast it to its type as it is IEnumerable not IEnumerable<T> See Enumerable.Cast :

Casts the elements of an IEnumerable to the specified type.

  var t = from c in connectionString.Cast<System.Configuration.ConnectionStringSettings>()
          select c.Name;
查看更多
登录 后发表回答