I have this list:
Spain_Finance
France_Sport
Spain_Politics
USA_Science
USA_Finance
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:
Spain_Finance
Spain_Politics
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
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();
if(SelectedCountries.Count>0)
Console.WriteLine("Selected Countries : {0}", String.Join(",",SelectedCountries));
else
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))
.Select(x=>x.Substring(x.IndexOf("_")+1))
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.