列出对象的整数

时间:2019-10-22 07:20:11

标签: c# list linq generics lambda

是否存在将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;
        }
    }
}

3 个答案:

答案 0 :(得分:3)

您应使用Enumerable.Select(来自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();

答案 1 :(得分:2)

认为,您正在询问类似car1.Neighbors.Select(x => cars[i]).ToList()之类的问题;坦白地说,我建议您存储一个引用列表,而不是一个 indices 列表-除非您有非常特殊的需求(通常与高级索引相关)策略)。与List<Car>一样的Neighbors可以更直接地工作,并且可以避免 lot 问题。如果您使用的是x86,它甚至不会花费任何额外费用;在x64上,是64位引用比32位整数大一点,但是:您要避免所有的间接操作和索引管理的所有问题。这样,这段代码就变成了字面意思:

var neighbors = car1.Neighbors;

答案 2 :(得分:1)

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

List<Car> TestList = new List<Car>(cars.Where(x => car1.Neighbors.Contains(x.Index)));