Reputation: 3256
I am using following code:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name"));
and i get keys like: name1, name2, name16, name18.
Now i want to create another array which will remove name and just keep 1,2,16,18. Is there any easy way to do this in above code itself? Or do it seperatly?
Upvotes: 1
Views: 859
Reputation: 28970
You can directly
ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(a => a.Replace("name",""));
Upvotes: 7
Reputation: 2605
I think your code is good enough. Just a little bit of performance improve by using substring as it's straightforward operation to remove prefix:
var prefix = "name"; // could be a parameter or used as const; just for example
var nums = ConfigurationManager.AppSettings.AllKeys.Where(s => s.StartsWith(prefix)).Select(s => s.Substring(prefix.Length)).ToArray();
Upvotes: 2
Reputation: 16651
I would not recommend relying on the position of the numeric value or the length of the string or the fact that the text reads 'name' at all. Instead you can use a simple regular expression to extract it consistently:
Regex regex = new Regex(@"[0-9]+");
var numbers = ConfigurationManager.AppSettings
.AllKeys.Select(p => regex.Match(p).Value).ToArray();
Upvotes: 0
Reputation: 61952
Use:
var namesWithoutPrefix = names.Select(n => n.Substring(4));
Doing Replace
instead of Substring
might replace several substrings in one name (and is slower even if it doesn't do so).
Upvotes: 0
Reputation: 3717
Try this:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(p => p.Replace("name", ""));
Upvotes: 1