问题描述
我有一个清单
i got a list
List<List<string>> myList
myList包含3个列表
list1 {a,b,c}
list2 {d,e, f}
list3 {g,h,k}
如何查找包含字符串d的列表索引
myList contains 3 lists
list1 {a,b,c}
list2 {d,e,f}
list3 {g,h,k}
how to find index of list that contains string "d"
推荐答案
private List<string> LoopFindExactMatch(List<List<string>> listolists, string matchtofind)
{
foreach(var listostring in listolists)
{
if(listostring.Contains(matchtofind))
{
return listostring;
}
}
return null;
或者,您可以使用Linq来简化代码:
Or, you could use Linq to simplify the code:
using System.Linq
private List<string> LinqFindExactMatch(List<List<string>> listolists, string matchtofind)
{
return listolists.FirstOrDefault(ll => ll.Contains(matchtofind));
}
测试:
private void testFindMatch()
{
List<string> list1 = new List<string> { "a", "b", "c" };
List<string> list2 = new List<string> { "d", "e", "f" };
List<string> list3 = new List<string> { "g", "h", "k" };
List<List<string>> ListOLists = new List<List<string>> {list1, list2, list3};
List<string> result1 = LoopFindExactMatch(ListOLists, "d");
List<string> result2 = LinqFindExactMatch(ListOLists, "d");
// test with string not in list
List<string> result3 = LoopFindExactMatch(ListOLists, "x");
List<string> result4 = LinqFindExactMatch(ListOLists, "y");
}
请注意,在这些示例中,我们仅搜索第一个匹配项。如果您的列表列表包含具有重复值的内部列表,则会显示另一个策略。
Note that in these examples we search for only the first match. If your list of lists contains 'inner' lists with duplicate values, another strategy is indicated.
list1 {"a","b","c"}
list2 {"d","e","f"}
list3 {"g","h","k"}
程序员的工作意味着有时候,你必须亲自动手并自己创造你需要的东西。就是这种情况。
这个案子非常简单,因为使用蛮力也是最好的方法。
你必须扫描你的列表,以扫描当前子列表的每个元素,当你得到一个匹配,只需返回你的索引,你就完成了。
我让你写代码,因为它可能是你的任务。
The job of programmer means that sometimes, you have to get your hands dirty and create yourself what you need. This is such a case.
This case is very simple because using brute force is also the best way to go.
You have to scan your list in order to scan each element of current sub-list, when you get a match, simply return your index and you are done.
I let you write the code as it is probably your assignment.
这篇关于c# - 如何在列表中查找列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!