如何检查字符串是否在列表中的列表中

时间:2017-03-15 05:27:41

标签: c# arrays list

我正在尝试验证IF内存在List<string>字符串。但List<string>位于List<List<string>> ..

请检查下面的code。它会抛出ArgumentException

loadTestList = new List<List<string>>();

loadTestList.ElementAt(loadTestSelect.SelectedIndex - 1).Contains(scorecardName);

请注意loadTestSelect是用户选择的下拉列表/选择。用户选择将被验证的List<string>

scoreCardName是我要搜索的字符串。

非常感谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

if(loadTestList.Any(x => x.Contains(scorecardName))
{
   // Proceed specified item is present in one sublist
}

如果您想根据loadTestSelect

中选定的索引检查仅包含在指定子列表中的以下内容
if(loadTestList[loadTestSelect.SelectedIndex].Contains(scorecardName))
{
   // Proceed specified item is present 
}

答案 1 :(得分:0)

尝试 Linq Any()两次

var loadTestList = new List<List<string>>() {
  new List<string>() {"a", "b", "c"},
  new List<string>() {"la-la-la"},
  new List<string>(),
  null,
  new List<string>() {"test", null, "sample"},
};

string scorecardName = "am"; // should be found in the "sample" 

var exists = loadTestList
  .Any(list => list != null && 
               list.Any(item => item != null && 
                                item.Contains(scorecardName)));