Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through a list and filter items starting with 'OO' in C#?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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".

  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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading