简体   繁体   中英

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?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM