英文:
How to filter the items starting with "OO" from the list
问题
我需要循环遍历List<string>
,然后提取以"OO"开头的指定项到一个新的字符串列表中。
这是我的代码:
List<string> myList = new List<string>()
myList.Add("5876575");
myList.Add("OO12571");
myList.Add("12287324");
myList.Add("87665751");
myList.Add("97213233");
myList.Add("87612222");
myList.Add("OO76566");
List<string> matches = myList.Where(x => x.StartsWith("OO")).ToList();
我的上面的代码不起作用。请帮助我。
输出应该是一个包含以"OO"开头的项的匹配列表:
Matches = OO12571, OO76566
英文:
I need to loop the List<string>
and then extract the specified items which start with "OO" to a new list of strings.
Here is my code:
List<string> mylist = new List<string>()
Mylist.add("5876575");
Mylist.add("OO12571");
Mylist.add("12287324");
Mylist.add("87665751");
Mylist.add("97213233");
Mylist.add("87612222");
Mylist.add("OO76566");
List<string> matches = new List<string>()
matches = myList.Where(x => x[0] == 'OO').ToList();
My above code is not working. Please help me.
The output should be a matches list which should only contain the item starts with "OO":
> Matches = OO12571, OO76566
答案1
得分: 2
string.StartsWith()
如@Charlieface建议的那样
matches = mylist.Where(x => x.StartsWith("OO"))
.ToList();
- 使用
string.Substring(0, 2)
获取前两个字符。
matches = mylist.Where(x => x.Substring(0, 2) == "OO")
.ToList();
- 使用正则表达式处理。
using System.Text.RegularExpressions;
Regex regex = new Regex("^OO");
matches = mylist.Where(x => regex.IsMatch(x))
.ToList();
英文:
Well, your attached code has plenty of compilation errors.
Assume that you have fixed it, there are quite some alternatives to filter the string in the array/list with starts with "OO".
string.StartsWith()
as suggested by @Charlieface
matches = mylist.Where(x => x.StartsWith("OO"))
.ToList();
- Take the first 2 characters with
string.Substring(0, 2)
.
matches = mylist.Where(x => x.Substring(0, 2) == "OO")
.ToList();
- Working with Regex.
using System.Text.RegularExpressions;
Regex regex = new Regex("^OO");
matches = mylist.Where(x => regex.IsMatch(x))
.ToList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论