我在List<string>()
中有多个ID
List<string> IDList = new List<string>() {
"ID101", //101
"I2D102", //102
"103", //103
"I124D104", //104
"ID-105", //105
"-1006" }; //1006
规则:字符串始终以长度为1到n且仅
int
的id结尾我需要将它们提取为
int
值。但是我的解决方案不起作用List<int> intList = IDList.Select(x => int.Parse(Regex.Match(x, @".*\d*").Value)).ToList();
最佳答案
这是另一种LINQ方法,如果数字始终在末尾且不可能为负值,则该方法有效。跳过无效的字符串:
List<int> intList = IDList
.Select(s => s.Reverse().TakeWhile(Char.IsDigit))
.Where(digits => digits.Any())
.Select(digits => int.Parse(String.Concat(digits.Reverse())))
.ToList();
(编辑:类似于Ian's approach)
关于c# - 从字符串末尾提取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37204880/