Joining Two list using LINQ Query and displaying only relevant data

Viewed 121

I am new to programming and working on LINQ, I have two list both have different data, the thing I am trying to do is join both of them in a separate list and then display only "Black" and "White" car data using LINQ (Query or IQueryable whatever it is) here is my code, that do entirely different thing

 static void Main(string[] args)
    {
        List<Cars> cars = new List<Cars>();
        cars.Add  (new Cars { Make = "Honda", Model = 2020, Color = "Black"});
        cars.Add  (new Cars { Make = "Suzuki", Model = 2020, Color = "White" });
        cars.Add  (new Cars { Make = "Toyota", Model = 2020, Color = "Green" });
        cars.Add  (new Cars { Make = "Kia", Model = 2020, Color = "Blue" });

        List<MakeBy> makeby = new List<MakeBy>();
        makeby.Add(new MakeBy { Color = "White", Country = "China" });
        makeby.Add(new MakeBy { Color = "Black", Country = "Japan" });
        makeby.Add(new MakeBy { Color = "White", Country = "Japan" });
        makeby.Add(new MakeBy { Color = "White", Country = "Korea" });



        var CombineCars = cars.Zip(makeby, (e, s) => e.Color + "White" + s.Color + "Black");

        foreach(var item in CombineCars)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();

    }
1 Answers

See if the following works. If not, please specify more precisely, what output you need.

var CombineCars = cars.Join(maekby,
    c => c.Color,
    m => m.Color,
    (c, m) => new
    {
        carMake = c.Make,
        carModel = c.Model,
        carColor = c.Color,
        makeByColor = m.Color,
        makeByCountry = m.Country
    });

Now you can access it like:

foreach (var car in CombineCars)
{
    Console.WriteLine($"Car model: {car.carModel}, car make: {car.carMake}"); //and so on
}

Haven't tested it, but it should do what you need.

Related