ラムダを使用して、片側だけで曲がっている車の数と、両側で曲がっている車の数を取得する方法は?
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