C# 从列表中获取项的索引<;int>;,当所有项目都相同时?
我试着为我的目的做每件事 我的场景是这样的: 我有一个列表,它看起来像这样(只有两个值,255和0):C# 从列表中获取项的索引<;int>;,当所有项目都相同时?,c#,list,loops,foreach,C#,List,Loops,Foreach,我试着为我的目的做每件事 我的场景是这样的: 我有一个列表,它看起来像这样(只有两个值,255和0): List<int> list = new List<int>(){ 255, 0, 0, 255, 0, 255, 255, 0, 255 }; 我的secondList如下所示: foreach(var item in list) { if(item == 255) { counter++; //its simple '
List<int> list = new List<int>(){ 255, 0, 0, 255, 0, 255, 255, 0, 255 };
我的secondList
如下所示:
foreach(var item in list)
{
if(item == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList.Contains(item); //its second list with ints
}
}
static List<int> secondList= new List<int>(){ 128, 1, 2, 64, 0, 4, 32, 16, 8 };
static List secondList=newlist(){128,1,2,64,0,4,32,16,8};
我想做的是,根据项的索引
从第二个列表
添加相同位置的值
如果item的index==1,我想将secondList也设置为位置“1”,并将其值添加到summary
变量中
据我所知,
Contains
将第一项作为item
返回,但正如您所看到的,在列表中,我只存储了两个值,255和0
是否可以在foreach
循环中正确获取项的索引?可以声明一个保存索引的变量,也可以使用foor循环:
int idx = 0;
foreach(var item in list)
{
if(item == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList[idx];
}
idx++;
}
最简单的解决方案是对
循环使用
int counter = 0;
int summary = 0;
List<int> list = new List<int>() { 255, 0, 0, 255, 0, 255, 255, 0, 255 };
List<int> secondList = new List<int>() { 128, 1, 2, 64, 0, 4, 32, 16, 8 };
for (int i = 0; i < list.Count; i++)
{
if (list[i] == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList[i]; //its second list with ints
}
}
int计数器=0;
int summary=0;
List List=新列表(){255,0,0,255,0,255,255,0,255};
List secondList=newlist(){128,1,2,64,0,4,32,16,8};
for(int i=0;i
您还可以使用更实用的方法,如
List<int> list = new List<int>(){ 255, 0, 0, 255, 0, 255, 255, 0, 255 };
List<int> secondList= new List<int>(){ 128, 1, 2, 64, 0, 4, 32, 16, 8 };
var matches = list.Zip(secondList, Tuple.Create)
.Where(t => t.Item1 == 255)
.Select(t => t.Item2);
Console.WriteLine(matches.Count());
Console.WriteLine(matches.Sum());
List List=newlist(){255,0,0,255,0,255,255,0,255};
List secondList=newlist(){128,1,2,64,0,4,32,16,8};
var matches=list.Zip(secondList,Tuple.Create)
.其中(t=>t.Item1==255)
.选择(t=>t.Item2);
Console.WriteLine(matches.Count());
Console.WriteLine(matches.Sum());
输出:
5
236
如果您也需要索引,那么使用for
循环要简单得多,因此迭代变量就是索引,您可以按索引访问元素。您想要的结果是什么?我尝试了这个,通过如何访问项?它简单吗secondList[iterator]
?它将==int
?类似于(例如)secondList[i]=64
?您应该真正开始使用自定义类。仅仅为了存储两个相关信息而使用两个相同大小的列表是不好的做法。相反,使用一个具有两个有意义属性的类,并将其实例放入列表
“据我所知,包含
将返回第一项,因为项
“包含”返回布尔值true/false,指示列表是否包含该项