Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16330

Use Linq to iterate over ConfigurationManager.ConnectionStrings?

Is it possible to do something like this?

var strings = ConfigurationManager.ConnectionStrings;

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

Upvotes: 2

Views: 2828

Answers (3)

Maxime BESSON
Maxime BESSON

Reputation: 31

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
}

Upvotes: 3

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

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;

Upvotes: 0

Jeroen Mostert
Jeroen Mostert

Reputation: 28799

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>().

Upvotes: 12

Related Questions