C# 如何在没有C类的情况下查找子列表的索引#
我想在listC# 如何在没有C类的情况下查找子列表的索引#,c#,arrays,indexof,C#,Arrays,Indexof,我想在listroute中找到包含特定值(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> s
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();
}
var route=newlist();
对于(int i=0;i让我们从一个示例开始(稍后我们将其转换为一个测试):
最后,我们希望将子列表索引作为结果:0
和2
。
如果是您的情况,我建议使用Linq
结果:
0, 2
编辑:如果只想有一个索引,则必须指定哪一个,例如,对于第一个索引,将.first()
而不是.ToArray()
:
您可以使用LINQ的Single
方法来检索给定谓词包含(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);
试试routeopt.x[i][j]
@Mairaj我应该在哪一部分试试?因为我已经说过routeopt.x是双数组[i,j]而不是[][]您的代码仍然有错误,您不能使用'var'。它说'Embedded statement cannot a declaration or labeled statement'@Arlita Nurmaya Asri:噢!但我可以使用var
;我已经从Visual Studio复制并粘贴了代码,它确实有效。您可以将var
更改为int[]
但是。我已经这样做了,但是错误仍然是一样的。如果var结果只是int
而不是int[]
?因为我想把它作为索引later@ArlitaNurmaya Asri:是的,这是错误的原因。让我们将我的结果
重命名为,比如,索引查找
您的代码已工作,但我希望索引为int
而不是int[]
,这样我就可以将其作为列表的索引
int value = 4;
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
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()
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);
int targetListIndex = routes.IndexOf(targetList); // 1 in this example