c# - 制作对象的整数列表
问题描述
是否有一个简短的形式(可能使用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;
}
}
}
解决方案
您应该使用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();
推荐阅读
- sql - 枢轴没有给出预期的结果
- protractor - 定位器是否应该等待,这是否会导致不稳定的测试?
- apache-spark - Apache Spark:为什么 spark 创建多个阶段来扫描甚至缓存的配置单元表,为什么重新分区可以解决这个问题?
- node.js - 在 Node.js 中拥有一个适用于应用程序生命周期的变量的最佳实践是什么?
- css - SVG 元素 CSS 过渡
在 Chrome 上标记 - javascript - 如何用里面的图像和文字编码进度圈?
- node.js - 未在 VPC 中调用 AWS Cognito 函数的问题
- amazon-cloudwatch - 我怎样才能通过电子邮件在 codepipeline 中发送失败的代码片段?
- typescript - 解决和组织给定文件夹中所有文件的导入
- android - 在 Android 上,用户取消时不会调用 AWSMobileClient.showSignIn 回调