如何计算仅在一侧转弯的汽车数量,以及使用lambda向两侧转弯的汽车数量?
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public Car(int _Id, string _Name)
{
Id = _Id;
Name = _Name;
}
}
public class Turn
{
public int Id { get; set; }
public string Name { get; set; }
public Turn(int _Id, string _Name)
{
Id = _Id;
Name = _Name;
}
}
public class CarTurn
{
public int Id { get; set; }
public Car Car { get; set; }
public Turn Turn { get; set; }
public CarTurn(int _Id, Car _Car, Turn _Turn)
{
Id = _Id;
Car = _Car;
Turn = _Turn;
}
}
.
Car car1 = new Car(1, "VW");
Car car2 = new Car(2, "Volvo");
Car car3 = new Car(3, "BMW");
Turn left = new Turn(1, "Left");
Turn right = new Turn(2, "Right");
CarTurn ct1 = new CarTurn(1, car1, left);
CarTurn ct2 = new CarTurn(2, car1, right);
CarTurn ct3 = new CarTurn(3, car2, right);
CarTurn ct4 = new CarTurn(4, car3, left);
List<CarTurn> data = new List<CarTurn>();
data.Add(ct1);
data.Add(ct2);
data.Add(ct3);
data.Add(ct4);
在这种情况下,结果应该是:
一侧:2
两侧:1
编辑
var groups = data.GroupBy(x => x.Car.Id);
var bothSides = groups.Count(g=> g.Any(x=> x.Turn.Id == 1) && g.Any(x=> x.Turn.Id == 2));
var oneSide = groups.Count(g=> (g.Any(x=> x.Turn.Id == 1) && !g.Any(x=> x.Turn.Id == 2))
|| (!g.Any(x=> x.Turn.Id == 1) && g.Any(x=> x.Turn.Id == 2)));
这是返回:
双面:1
单面:0