Существует ли краткая форма (возможно, использующая LINQ
) для создания integers
до objects
и добавления их в List
?
Я думаю, что-то вроде List<Car> TestList = car1.Neighbors.To(c => cars[c]);
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Cars
Car car0 = new Car(0, new List<int> { 1 });
Car car1 = new Car(1, new List<int> { 0, 2 });
Car car2 = new Car(2, new List<int> { 1 });
List<Car> cars = new List<Car> { car0, car1, car2 };
// THIS I WANT TO SHORTEN ▼▼▼▼▼▼▼▼▼▼
List<Car> TestList = new List<Car>();
foreach (int i in car1.Neighbors)
TestList.Add(cars[i]);
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
Console.Write("Neighbors of car 1:");
foreach (Car car in TestList)
Console.Write(" car" + car.Index);
}
public class Car
{
public int Index; // index of the car
public List<int> Neighbors; // car indexes, that are parked near to this car
public Car (int index, List<int> neighbors)
{
Index = index;
Neighbors = neighbors;
}
}
}