如何从asp.net中包含确定字符串值的字符串列表中获取项目?

时间:2016-09-20 07:40:25

标签: c# asp.net vb.net list arraylist

我有这个清单:

    Spain_Finance
    France_Sport
    Spain_Politics
    USA_Science
    USA_Finance

我使用此代码检查列表是否包含确定值:

 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

所以在if语句中执行此操作后,我需要从包含西班牙语的列表中获取元素 结果将是:

 Spain_Finance
 Spain_Politics

我正在寻找一个简单的代码来执行此操作,我可以做一个foreach并将国家/地区的名称与项目列表进行比较,但我想知道是否有更简单的方法,这是为了学习,我感谢您的贡献,谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用Where代替Any,因此代码如下:

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

由于问题也标记为c#,因此Example会对您有所帮助,即代码将为:

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");

更新:您可以使用Select后跟Where.SubString代码将是这样的

List<string> SelectedCountries = countryList.Where(x => x.Contains(namecountry))
                                                         .Select(x=>x.Substring(x.IndexOf("_")+1))
                                                         .ToList();