Azerty123 Azerty123 - 4 months ago 17
C# Question

Linq relation of two list

I have two class :

public class Car
{
public string Color { get; set; }

public string Speed { get; set; }
}

Public class Shop
{
public string Color { get; set; }

public string Speed { get; set; }
}


And two instance : List and List.

In my List for all index, I have not a property speed

How to do the relation (Where color of list = color of list) for fill the property Speed of my different index in list ?

For example :

List<Car> Cars = new List<Car>()
{
new Car()
{
Color = "Green",
Speed = "100"
},
new Car()
{
Color = "Yellow",
Speed = "150"
}
}

List<Shop> Shops = new List<Shop>()
{
new Shop()
{
Color = "Green"
},
new Shop()
{
Color = "Yellow"
}
}


And expected output :

List<Shop> Shops = new List<Shop>()
{
new Shop()
{
Color = "Green",
Speed = "100"
},
new Shop()
{
Color = "Yellow",
Speed = "150"
}
}

Answer

You want something like that?

public class Car
{
    public string Color { get; set; }    
    public int Speed { get; set; }
}

public class Shop
{
    public string Color { get; set; }    
    public int Speed { get; set; }
}

public class Program
{
    public static void Main()
    {
        var carsList = new List<Car>();
        carsList.Add(new Car {Color = "Green", Speed = 200});

        var shopsList = new List<Shop>();
        shopsList.Add(new Shop {Color = "Green"});          

        foreach(var item in shopsList)
        {
            var match = carsList.FirstOrDefault(car => car.Color == item.Color);
            //Post c# 6.0
            item.Speed = match?.Speed;

            //Pre c# 6.0
            item.Speed = match == null ? 0 : match.Speed;
        }               
    }
}