I'm using Xamarin Forms 5.0 and C# 8.0 and would like to validate least conditions from the 2 following scenarios: *Provided JSON data
{
"part": [
{
"id": "1234",
"name": "part 1234"
},
...
],
"car": [
{
"id": "002",
"name": "car 02",
"parts_list": [
{
"id": "1234",
"is_in_use": 1
},
...
]
},
...
]
}
Scenario 1: Validate all parts in the "part" list are being used by at least one car. Return false if exist one part that is not used by any of the cars in "car" list.
Scenario 2: Validate all cars in the "car" list uses at least one part in the "part" list. Return false if exist one car that uses no parts in the "part" list.
Provided that the "part" and "parts_list" contains the same number of elements and those elements has the same id. The "is_in_use" flag equals to 1 or 0 indicates that part id is use or not use in the car.
Question:
- How can I validate these 2 scenarios in C#?
- In which way that is better for performance and which way provides cleaner code?
I've tried using Linq but so far still get wrong results for the scenario 1. Please forgive my bad English!
CodePudding user response:
Scenario 1 Note this is, in effect, two Linq queries. The inner (indented) query creates an enumerable of distinct part keys in use across all cars. The outer query simply returns a list of ids of any parts which aren't in that list.
private static bool AllPartsAreInUse(Model model)
{
return !model.part
.Where(p => !model.car
.SelectMany(c => c.parts_list) // combine all car part lists
.GroupBy(pl => pl.id) // group by the part id
.Select(pl => pl.Key) // select the part ids
.Contains(p.id)) // check if this part is present
.Any();
}
Scenario 2 This is the easy one, as you say, because you just need to find any cars with any empty parts list.
private static bool AllCarsAreInUse(Model model)
{
return !model.car
.Where(c => !c.parts_list.Any())
.Any();
}
CodePudding user response:
class Part
{
public int Id { get; set; }
public string Name{ get; set; }
}
class Car
{
public int Id { get; set; }
public string Name { get; set; }
public List<CarPartItem> Parts{ get; set; }
}
class CarPartItem
{
public int Id { get; set; }
public bool IsInUse { get; set; }
}
class ComplexType
{
public List<Part> Parts{ get; set; }
public List<Car> Cars{ get; set; }
}
class Program
{
static void Main(string[] args)
{
var part1 = new Part { Id = 1234, Name = "part 1234" };
var car1 = new Car { Id = 002, Name = "car 02", Parts = new List<CarPartItem> { new CarPartItem { Id = 1234, IsInUse = true } }};
var json = new ComplexType { Cars = new List<Car> { car1 }, Parts = new List<Part> { part1 } };
var scenerio1 = json.Parts.Exists(part => json.Cars.Exists(car => car.Parts.Exists(p => p.Id == part.Id)));
var scenerio2 = json.Cars.Exists(car => car.Parts.Exists(cp => json.Parts.Exists(p => p.Id == cp.Id)));
}
}