我想在列表 route
中找到包含特定值 (i) 的子列表的索引,但我不想对其进行分类。
这是我的代码:
var route = new List<List<int>>();
for (int i = 0; i<DC1; ++i)
{
for (int j = 0; j<DC1; ++j)
{
if (routeopt.x[0, j] == 1)
{
List<int> subroute = new List<int>();
if (routeopt.x[i, j] == 1)
{
subroute.Add(j);
route.Add(subroute);
}
}
}
if(i == 0) continue;
for (int j = 1; j<DC1;j++ )
{
if (routeopt.x[i, j] == 1)
route[route.IndexOf(i)].Add ( j);
}
}
foreach (var subroute in route)
{
Console.Write("subroute: ");
foreach (int s in subroute)
Console.Write(s + " ");
Console.WriteLine();
}
例如,基于这段代码:
for (int j = 1; j < DC1;j++ )
{
if (routeopt.x[i, j] == 1)
route[route.IndexOf(i)].Add(j);
}
我想做如果 x[1,3] == 1
那么我可以将 3 添加到包含 1 的子列表中。
这段代码 route.IndexOf(i)
仍然是红色下划线,请帮助如何更正它。谢谢
最佳答案
您可以使用 LINQ 的 Single
方法在给定谓词 Contains(i)
的情况下检索您想要的特定列表。在这里,我要查找包含 6 的列表,并向其中添加 7。
var routes = new List<List<int>>()
{
new List<int>() {1, 2, 3},
new List<int>() {4, 5, 6},
};
List<int> targetList = routes.Single(i => i.Contains(6));
targetList.Add(7);
要具体获取该列表的索引,您可以使用 IndexOf
方法,例如:
int targetListIndex = routes.IndexOf(targetList); // 1 in this example
关于c# - 如何在没有 C# 类的情况下查找子列表的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41996535/