开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜