如何从列表中筛选以“OO”开头的项目。

huangapple go评论82阅读模式
英文:

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

  1. string.StartsWith() 如@Charlieface建议的那样
matches = mylist.Where(x => x.StartsWith("OO"))
    .ToList();
  1. 使用 string.Substring(0, 2) 获取前两个字符。
matches = mylist.Where(x => x.Substring(0, 2) == "OO")
    .ToList();
  1. 使用正则表达式处理。
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".

  1. string.StartsWith() as suggested by @Charlieface
matches = mylist.Where(x => x.StartsWith("OO"))
	.ToList();
  1. Take the first 2 characters with string.Substring(0, 2).
matches = mylist.Where(x => x.Substring(0, 2) == "OO")
	.ToList();
  1. Working with Regex.
using System.Text.RegularExpressions;

Regex regex = new Regex("^OO");
matches = mylist.Where(x => regex.IsMatch(x))
	.ToList();

huangapple
  • 本文由 发表于 2023年5月25日 09:08:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定