Thorin Oakenshield
Thorin Oakenshield

Reputation: 14662

How to remove substring from all strings in a list in C# using LINQ

I have a list of strings like

"00000101000000110110000010010011",
"11110001000000001000000010010011",

I need to remove the first 4 characters from each string

so the resulting list will be like

"0101000000110110000010010011",
"0001000000001000000010010011",

Is there any way to do this using LINQ?

Upvotes: 2

Views: 4307

Answers (2)

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

With linq only :

l.Select(s => new string(s.Skip(4).ToArray())).ToList();

or using Substring

l.Select(s => s.Substring(4)).ToList();

But with the limitations that Quartermeister noted (Exception if the strings are too small)

Upvotes: 1

Quartermeister
Quartermeister

Reputation: 59139

strings = strings.Select(s => s.Substring(4)).ToList();

That will throw an ArgumentOutOfRange exception if the string is not at least four characters long, so you may want to do something like

strings = strings.Where(s => s.Length >= 4).Select(s => s.Substring(4)).ToList();

to remove strings that are too short.

Upvotes: 8

Related Questions