Esraa_92 Esraa_92 - 1 year ago 46 Question

How can I get the items from a list of string that contain a determinate string value in

I have this list:


I use this code to check if the list contains a determinate value:

Dim namecountry As String = "Spain"
Dim listcontainscountry As Boolean = mylistofcountries.Any(Function(l) l.Contains(namecountry))
If listcontainscountry = True Then
' Here I need to get the elements from the list that contains Spain
End If

So after doing this inside the if statement I need to get the elements from the list that contains Spain
The result will be this:


I looking for a simple code to do this, I can do a foreach and compare the name from country with the item list, but I want to know is there another way more simple, this is for learn, I appreciate your contribution, thanks

Answer Source

You can use Where instead for Any so the code will be like the following:

Dim namecountry As String = "Spain"
Dim listcontainscountry = mylistofcountries.Where(Function(l) l.Contains(namecountry)).ToList()

Since the question is tagged to c# also, this Example will help you, that is the code will be :

List<string> countryList = new List<string>() { "Spain_Finance", "France_Sport", "Spain_Politics", "USA_Science", "USA_Finance" };
string namecountry = "Spain";
List<string> SelectedCountries = countryList.Where(x => x.Contains(namecountry)).ToList();
   Console.WriteLine("Selected Countries : {0}", String.Join(",",SelectedCountries));
   Console.WriteLine("No Matches ware found");

update: You can use Select followed by Where and .SubString the code will be like this

List<string> SelectedCountries = countryList.Where(x => x.Contains(namecountry))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download