我有一个包含节点列表的Model对象。这些节点包含签名。
我想拥有一个带有getter的属性,返回一组签名。我无法实例化数组,我不确定是否应该使用数组/列表/枚举或其他内容。
你将如何实现这一目标?
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var m = new Model();
Console.WriteLine(m.Signatures.ToString());
Console.ReadLine();
}
}
public class Model
{
public List<Node> Nodes { get; set; }
public int[][] Signatures
{
get
{
return Nodes.Select(x => x.Signature) as int[][];
}
}
public Model()
{
Nodes = new List<Node>();
Nodes.Add(new Node { Signature = new[] { 1,1,0,0,0 } });
Nodes.Add(new Node { Signature = new[] { 1,1,0,0,1 } });
}
}
public class Node
{
public int[] Signature { get; set; }
}
}
答案 0 :(得分:2)
使用ToArray()
return Nodes.Select(x => x.Signature).ToArray();
这样的东西可以正确输出:
Array.ForEach(m.Signatures, x=>Console.WriteLine(string.Join(",", x)));
答案 1 :(得分:1)
在Signatures
媒体资源中,您尝试使用as
运算符将类型转换为int[][]
。然而,Select
方法返回IEnumerable<int[]>
,它不是数组。使用ToArray
创建数组:
public int[][] Signatures
{
get
{
return Nodes.Select(x => x.Signature).ToArray();
}
}