-1

I have a list of a certain type which looks like this:

class DestinationType {
    public string FruitName { get; set; }    
    public string VegetableName { get; set; }
}

What I want to do is create a list of the above type DestinationType and add elements to it from two different List of type string. The lists that have the values that I want to add to DestinationType looks like the ones below:

fruitList = List<string> { "apple", "orange" }

vegetableList = List<string> { "celery", "pumpkin" }

How can I add the elements from fruitList and vegetableList such that the end result would look like the one here?

List<DestinationList> theCompleteDestinationItem =
 [
    {
        fruitName: "apple",
        vegetableName: "celery"
    },
    {
        fruitName: "orange",
        vegetableName: "pumpkin"
    }
]
suM88
  • 9
  • 2

2 Answers2

0

You could use the Enumerable.Zip to combine the elements of both lists then project into a type of your choosing or an anonymous type or ValueTuple

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

Given

var fruitList = new List<string> {"apple", "orange"};
var vegetableList = new List<string> {"celery", "pumpkin"};

Example

var results = fruitList.Zip(vegetableList, (fruit, vegetable) => new {fruit, vegetable});

foreach (var result in results)
   Console.WriteLine($"{result.fruit}, {result.vegetable}");

Output

apple, celery
orange, pumpkin

Or if you have a readymade type

public class Destination
{
   public string Fruit { get; set; }
   public string Vegetable { get; set; }
}

...

var results = fruitList.Zip(vegetableList, (fruit, vegetable) => 
   new Destination( )
   {
      Fruit = fruit,
      Vegetable = vegetable
   });
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

you could use zip:

        var fruitList = new List<string> { "apple", "orange" };
        var vegetableList = new List<string> { "celery", "pumpkin" };
        var fruitAndVeggies = fruitList.Zip(vegetableList, (fruit, veggie) => new DestinationType() { FruitName = fruit, VegetableName = veggie});
audzzy
  • 721
  • 1
  • 4
  • 12