Rod
Rod

Reputation: 15455

remove quote from list<string> using linq

I have a List strings and each value has a leading quote that needs to be removed. Now there could be quotes further down the string and those will need to stay.

List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");

Is there a linq way?

Upvotes: 0

Views: 1894

Answers (5)

Brownman98
Brownman98

Reputation: 1065

strings.ForEach(s => s = s.TrimStart('\''));

EDIT by Olivier Jacot-Descombes (it demonstrates that this solution does not work):

List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");

Console.WriteLine("Before:");
foreach (string s in strings) {
    Console.WriteLine(s);
}

strings.ForEach(s => s = s.TrimStart('\''));

Console.WriteLine();
Console.WriteLine("After:");
foreach (string s in strings) {
    Console.WriteLine(s);
}
Console.ReadKey();

This produces the following output on the console:

Before:
'Value1
'Values2 This 2nd ' should stay

After:
'Value1
'Values2 This 2nd ' should stay

Upvotes: 0

itsme86
itsme86

Reputation: 19496

LINQ is really unnecessary for this. You could just use TrimStart() by itself:

strings.Add("'Value1".TrimStart('\''));

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112372

var result = strings.Select(s => s.TrimStart('\''));

Note: This will remove all leading occurrences of ('). However, I assume that you will not have a string like "''Value1".

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

strings = strings.Select(x => x.StartsWith("'") ? x.Substring(1) : x).ToList();

Upvotes: 4

Chris Shain
Chris Shain

Reputation: 51339

strings.Select(s => s.StartsWith("'") ? s.Substring(1) : s);

Upvotes: 3

Related Questions