首页 > 解决方案 > 制作对象的整数列表

问题描述

是否有一个简短的形式(可能使用LINQ)来制作integers并将objects它们添加到 a 中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;
        }
    }
}

标签: c#listlinqgenericslambda

解决方案


您应该使用Enumerable.Select(from System.Linq) 将序列的每个元素投影成新形式 ( https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8 )

IEnumerable<Car> TestList = car1.Neighbors.Select(i => cars[i]);

或者如果你绝对需要一个列表

List<Car> TestList = car1.Neighbors.Select(n => cars[n]).ToList();

推荐阅读