给出具有不同参数的对象列表,如何将参数值分组到一个列表中并将其绑定到另一个对象:我正在使用c#中的dictionary进行尝试: 示例:class car :(更新:使用好的解决方案,工作代码获取嵌套的dico)
Two
答案 0 :(得分:1)
理想情况下,您应该修改架构以使其更简单,例如在db中创建一个表,该表代表每种车型必须提供的颜色选项。
话虽如此,这是一个使用您当前架构进行操作的示例。有几种方法可以做到,我选择了最适合我的方法。首先,您按组合键,Id和颜色分组。然后仅按ID分组,这样便有一组分组,从中选择具有该颜色的第一辆汽车。
这里是Fiddle,以显示其正常工作
public class Car{
public int Id;
public Color Color;
}
public class Color
{
public int Id;
public string ColorName;
}
public static void Main()
{
var carList = new List<Car> {
new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
new Car() { Id = 1, Color = new Color {Id = 1, ColorName = "blue" }},
new Car() { Id = 1, Color = new Color {Id = 2, ColorName = "red" }},
new Car() { Id = 1, Color = new Color {Id = 3, ColorName = "green" }},
};
var carColorMap = carList.GroupBy(x => new {x.Id, ColorId = x.Color.Id}).GroupBy(x => x.Key.Id).ToDictionary(x => x.Key, v => v.Select(x => x.FirstOrDefault()));
foreach(var car in carColorMap)
{
Console.WriteLine(car.Key);
foreach(var color in car.Value)
Console.WriteLine(color.Color.ColorName);
}
}
答案 1 :(得分:0)
阅读时
var listOfCars = new list<Car>();
var firstCar = new Car(firstCarId,fisrtCarColor);
var secondCar = new Car(firstCarId,secondCarColor);
var thirdCar = new Car(firstCarId,thirdCarColor);
listOfCars.Add(firstCar);
listOfCars.Add(secondCar);
listOfCars.Add(thirdCar);
看起来您只需要一辆载有3种颜色的汽车。因此,要么您过度简化了代码,使其无法反映现实情况,要么您的解决方案设计过度,并使事情看起来复杂。然后,您可以像下面那样简化设计,以使事情变得简单:
public sealed class Car
{
private readonly HashSet<Color> _colors;
public Car(Id id, params Color[] colors)
{
Id = id;
_colors = new HashSet<Color>(colors);
}
public Id Id { get; }
public IReadOnlyCollection<Color> Colors => _colors;
}
用法:
var car = new Car(carId, color1, color2, color3);
Console.WriteLine(car.Id);
foreach (var color in car.Colors)
{
Console.WriteLine(color);
}