I need to loop the List and then extract the specified items which starts with ‘OO’ to New list
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.
Output should be Matches list should only contains any item in the list which starts with ‘OO’ :-
Matches = OO12571, OO76566
>Solution :
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();