-1

I have the following foreach loop in a c# project which loops through list items and it limits it to only show 3

And in my

What I need to do is replace th in the key instead.

I'm guessing it's meant to be

shaneklive
  • 59
  • 7
  • can you take one int variable and then get the config value into that variable and pass that variable to your Take() ? – Ankit Jan 19 '17 at 09:09

1 Answers1

3

To access App/Web.config you can use ConfigurationManager:

int value = (int)System.Configuration.ConfigurationManager.AppSettings["TrendingNavLimit"];

Please follow that article for more details: https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx

If we put it all together, solution could be:

int value = (int)ConfigurationManager.AppSettings["TrendingNavLimit"];
foreach (NavigationItem item in items.Take(value))
{
    @NavigationHelper.SimpleNavLink(config, item, absoluteUrls);
}

In terms of SOLID, I would re-thing approach though.

I would create an interface - IConfigProvider with property TrendingNavLimit {get;} and implement that interface in default class, that will use ConfigurationManager to retrieve data, and then inject it in you class.

madoxdev
  • 3,770
  • 1
  • 24
  • 39
  • this is what I mean in the question comment – Ankit Jan 19 '17 at 09:11
  • Thanks, when I try that and try to publish the project I get the error "The name configurationManager does not exist in the current context" – shaneklive Jan 19 '17 at 09:47
  • use full namespace or add `using System.Configuration;` on top of your class. In C# configurationManager is not same as ConfigurationManager. You may be missing a reference as well, make sure you have reference to System.Configuration in your project. – madoxdev Jan 19 '17 at 09:52