如何找到没有C类的子列表索引#

时间:2017-02-02 07:35:26

标签: 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)仍然是红色下划线,请帮助如何纠正它。感谢

2 个答案:

答案 0 :(得分:2)

让我们从示例开始(我们稍后将其转换为 test ):

 List<List<int>> route = new List<List<int>>() {
   new List<int>() {1, 2, 3, 4, 5}, // sublist #0: contains value == 4
   new List<int>() {7, 8, 2, 9},    // sublist #1: doesn't contain value == 4
   new List<int>() {9, 10, 4},      // sublist #2: contains value == 4
 };

我们正在寻找每个子列表中的value

 int value = 4;

最后,我们希望将子列表索引作为结果:02。 如果是你的情况,我建议使用 Linq

List<List<int>> route = new List<List<int>>() {
  new List<int>() {1, 2, 3, 4, 5}, 
  new List<int>() {7, 8, 2, 9},    
  new List<int>() {9, 10, 4}, 
};

int value = 4;

var indexesFound = route
  .Select((sublist, index) => new { // eh, new class, but anonymous one
     sublist = sublist,
     index = index, }) 
  .Where(chunk => chunk.sublist.Contains(value))
  .Select(chunk => chunk.index)
  .ToArray(); // if you want, say, array materialization

测试

Console.Wrire(string.Join(", ", indexesFound));

结果:

0, 2

修改:如果您只想拥有一个索引,则必须指定哪个索引,例如对于第一个索引放置.First()而不是.ToArray()

int firstIndexFound = route
  .Select((sublist, index) => new { // eh, new class, but anonymous one
     sublist = sublist,
     index = index, }) 
  .Where(chunk => chunk.sublist.Contains(value))
  .Select(chunk => chunk.index)
  .First(); // or .Last()

答案 1 :(得分:1)

您可以使用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