Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of sublist without class C#

Tags:

arrays

c#

indexof

I want to find the index of sublist in list route which contains certain value(i), but I don't want to make a class of it. Here is my code:

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 example, based on this code:

for (int j = 1; j < DC1;j++ )
{
     if (routeopt.x[i, j] == 1)
     route[route.IndexOf(i)].Add(j);
}

I want to make if x[1,3] == 1 then I can add 3 to sublist which contains 1. this code route.IndexOf(i) is still get red underline, please help how to correct it. Thanks

like image 994
Arlita Nurmaya Asri Avatar asked Dec 05 '25 05:12

Arlita Nurmaya Asri


1 Answers

You can use LINQ's Single method to retrieve the specific list you want given a predicate Contains(i). Here I am looking for the list that contains 6, and adds 7 to it.

 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);

To get specifically the index of that list, then you can use IndexOf method like:

 int targetListIndex = routes.IndexOf(targetList); // 1 in this example
like image 126
Ghasan غسان Avatar answered Dec 07 '25 18:12

Ghasan غسان



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!