Question

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; }
    }
}
Was it helpful?

Solution 2

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();
    }
}

OTHER TIPS

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)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top