Reputation: 104
I have a Model object that contains a list of node. These nodes contain a signature.
I would like to have a property with a getter returning an array of signatures. I have trouble to instantiate the array and I'm not sure if I should use an array/list/enumerable or something else.
How would you achieve this?
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; }
}
}
Upvotes: 0
Views: 216
Reputation: 1989
Use ToArray()
return Nodes.Select(x => x.Signature).ToArray();
And something like this to output it correctly:
Array.ForEach(m.Signatures, x=>Console.WriteLine(string.Join(",", x)));
Upvotes: 2
Reputation: 3123
In your Signatures
property you try to use the as
operator to convert the type into int[][]
. The Select
method however returns an IEnumerable<int[]>
which is not an array. Use ToArray
to create the array:
public int[][] Signatures
{
get
{
return Nodes.Select(x => x.Signature).ToArray();
}
}
Upvotes: 1