我有以下代码:
IEnumerable<Vehicles> Vehicles;
for (int count = 0; count < Vehicles.Count(); count++)
{
if (Vehicles.ElementAt(count).Mode)
{
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用if条件实现Lambda表达式foreach?
我试过这个:
Vehicles.ToList().ForEach(i=>i.Mode)
Run Code Online (Sandbox Code Playgroud)
并且由于我不知道如何检查条件,因为intellisense也没有显示where子句,所以对此感到震惊.任何帮助非常感谢.我想在循环中使用计数值....
Tim*_*ter 12
我认为Mode是一个bool财产.然后你只需要这个小查询和一个foreach:
foreach(Vehicles v in Vehicles.Where(x => x.Mode))
{
// do something with it
}
Run Code Online (Sandbox Code Playgroud)
你的方法非常低效.如果Vehicles不是列表或数组,则Vehicles.Count()枚举整个查询以计算计数.更糟糕的是ElementAt在循环中使用 ,因为它也会枚举整个序列,直到它处于给定的索引,但即使是每次迭代也是如此.
使用的最后一种方法Vehicles.ToList().ForEach是创建一个新列表,没有明显的原因,只是为了能够使用ForEach没有普通foreach循环的优势的方法.它也不过滤这个属性的车辆.
如果你需要一个评论的计数器,你只需要增加一个局部变量:
int count = 0;
foreach(Vehicles v in Vehicles.Where(x => x.Mode))
{
count++;
// do something with it
}
Run Code Online (Sandbox Code Playgroud)
或者直接在LINQ查询中选择索引为匿名类型:
var modeVehicles = Vehicles
.Where(x => x.Mode)
.Select((x, index) => new { Count = index + 1, Vehicle = x });
foreach(var x in modeVehicles)
{
int count = x.Count;
Vehicles v = x.Vehicle;
// do something with it
}
Run Code Online (Sandbox Code Playgroud)
两种方法都返回与谓词匹配的车辆数量(Mode是true).
如果您想要在所有车辆(包括不匹配车辆)中使用此车辆的数量,您有三种选择:
1.)如果它实际上是一个列表或数组(在这种情况下首选),则使用for循环:
var list = Vehicles as IList<Vehicles>;
if(list != null)
{
for (int count = 0; count < list.Count; count++)
{
if (list[count].Mode)
{
// do something with it
}
}
}
Run Code Online (Sandbox Code Playgroud)
2.)使用平原foreach和if:
int count = 0;
foreach(Vehicles v in Vehicles)
{
if (v.Mode)
{
// do something with it
}
count++;
}
Run Code Online (Sandbox Code Playgroud)
3.)或像这样的LINQ查询(注意在之前首先选择索引Where):
var modeVehicles = Vehicles
.Select((x, index) => new { Count = index + 1, Vehicle = x })
.Where(x => x.Mode);
foreach (var x in modeVehicles)
{
int count = x.Count;
Vehicles v = x.Vehicle;
// do something with it
}
Run Code Online (Sandbox Code Playgroud)