0

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; }
    }
}
1
  • 1
    Have you tried: Nodes.Select(x => x.Signature).ToArray() ? Commented Nov 2, 2013 at 22:17

2 Answers 2

2

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)));
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks, can't believe it was this simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.