【问题标题】:How can I get the items from a list of string that contain a determinate string value in asp.net?如何从包含 asp.net 中确定字符串值的字符串列表中获取项目?
【发布时间】:2017-01-28 00:56:48
【问题描述】:

我有这个清单:

    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 并将国家/地区的名称与项目列表进行比较,但我想知道是否有另一种更简单的方法,这是为了学习,感谢您的贡献,谢谢

【问题讨论】:

  • 你为什么被标记为c#?用vb代码?
  • 因为即使答案是c#我也可以把它翻译成vb.net
  • 如果您的问题不是特定于某种语言,则不要将其标记为特定于该语言。

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


【解决方案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();

【讨论】:

  • 非常感谢您的帮助,我还有一个问题,可以使用相同的代码获取部分名称列表,例如:Finance, Politics?
  • 由于OP也需要知道是否有物品:Dim containsCountries = listcontainscountry.Count &gt; 0。微不足道,但这样他就不需要另一个Any-query。
  • @Esraa_92 : 你的问题不够清楚,输入是什么,预期的输出是什么?
  • @un-lucky :我问是否可以使用相同的示例获得部分名称,从本例中的示例中我得到以下结果:Spain_Finance,Spain_Politics ,但是如果我想获得这些部分怎么办国家/地区,例如:金融、政治
  • @Esraa_92 从我可以看到上面的代码也适用于此。
猜你喜欢
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多