NoviceMe
NoviceMe

Reputation: 3256

How to easily remove part of string from string array in c#

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

Answers (5)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can directly

ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(a => a.Replace("name",""));

Upvotes: 7

aiodintsov
aiodintsov

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

kprobst
kprobst

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

Jeppe Stig Nielsen
Jeppe Stig Nielsen

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

Grant H.
Grant H.

Reputation: 3717

Try this:

var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(p => p.Replace("name", ""));

Upvotes: 1

Related Questions