c# - 如何在没有 C# 类的情况下查找子列表的索引

标签 c# arrays indexof

我想在列表 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/

相关文章:

非关联数组上的 PHP in_array 行为

C++ 指针的内存地址和指针数组的内存地址如何相同?

java - 打印 aLine 并删除第一个 'c' 'C' 'd' 或 'D'

c++ - 堆或栈数组。用户定义的类型难题

java - 查找 String 数组中索引处元素的子字符串

AngularJS ng-class 检查嵌套键/值对是否存在,然后将值添加为类

c# - 安装配置文件服务 - 配置文件安装失败(从 iOS 获取 UDID)

c# - 打开 XML 表头同一页

c# - 如何使用 C# 访问共享点数据?

c# - C# MVC 中的 Linq 百分比