You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取数组中每个对象的属性?C#卡牌游戏提取卡牌颜色参数问题

解决方案

方法1:使用LINQ实现(代码最简洁)

首先需要在代码文件顶部引入LINQ命名空间:
using System.Linq;
之后直接调用Select方法遍历列表转换即可:

int[] cardColors = address1Player.Select(address => PropertyColor(address)).ToArray();
// 也可以简写成方法组的形式:
// int[] cardColors = address1Player.Select(PropertyColor).ToArray();

Select会自动遍历address1Player中的每一个卡牌ID,传入PropertyColor方法得到对应的颜色值,最后调用ToArray()直接转换为int数组。

方法2:手动循环遍历(无需依赖LINQ)

如果项目不需要引入LINQ,可以用基础的for循环实现:

// 先创建和卡牌列表长度相同的int数组
int[] cardColors = new int[address1Player.Count];
// 遍历每个卡牌ID,查询颜色存入数组
for (int i = 0; i < address1Player.Count; i++)
{
    cardColors[i] = PropertyColor(address1Player[i]);
}

注意事项

  • 执行转换前请确保address1Player中存储的所有卡牌ID都是合法值,不会超出allProperties数组的索引范围,避免触发索引越界异常。

内容的提问来源于stack exchange,提问作者Korsun Pavel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:36:04