如何计算仅在一侧转弯的车辆数量,以及使用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 oneSide:0
答案 0 :(得分:1)
像这样的东西(属性名称想象):
var groups = data.GroupBy(x => x.CarId);
var bothSides = groups.Count(g=> g.Any(x=> x.IsLeftTurn) && g.Any(x=> x.IsRightTurn);
var oneSide = groups.Count(g=> (g.Any(x=> x.IsLeftTurn) && !g.Any(x=> x.IsRightTurn))
|| (!g.Any(x=> x.IsLeftTurn) && g.Any(x=> x.IsRightTurn);
答案 1 :(得分:1)
var carTurns = new[] { ct1, ct2, ct3, ct4 };
var groupedCarTurns = carTurns.GroupBy(ct => ct.Car);
var oneSideCount = groupedCarTurns.Count(group =>
group.All(ct => ct.Turn == right) ||
group.All(ct => ct.Turn == left);
var bothSides = groupedCarTurns.Count(group =>
group.Any(ct => ct.Turn == right) &&
group.Any(ct => ct.Turn == left);