creating same type of objects based on a condition from an existing object ; C# LINQ
I am trying to breakdown an object into more than one object of same type based on a condition. How can I write a LINQ query in C# for this.
public class Order
{
public List<Driver> Drivers { get; set; }
public List<Vehicle> Vehicles {开发者_如何学C get; set; }
}
Order co = new Order();
Say for example my co object has 14 drivers and 12 vehicles.
I want to create objects of type Order which will contain 5 drivers and 4 vehicles.
if (co.Drivers.count > 5 || co.vehicles.count > 4)
{
//Break the total number of Drivers and Vehicles into sets of 5 and 4 and add them to the Orde object.
}
Thanks BB
var newOrders = new List<Order>();
for (int drivers = 0, vehicles = 0;
drivers < co.Drivers.Count || vehicles < co.Vehicles.Count;
drivers += 5, vehicles += 4)
{
newOrders.Add(new Order {
Drivers = co.Drivers.Skip(drivers).Take(5),
Vehicles = co.Vehicles.Skip(vehicles).Take(4)
}));
}
精彩评论