简体   繁体   English

C#锯齿状数组获取属性实例化LINQ

[英]C# jagged array get property instantiate linq

I have a Model object that contains a list of node. 我有一个包含节点列表的Model对象。 These nodes contain a signature. 这些节点包含一个签名。

I would like to have a property with a getter returning an array of signatures. 我想有一个带有getter的属性,该属性返回签名数组。 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; }
    }
}

Use ToArray() 使用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)));

In your Signatures property you try to use the as operator to convert the type into int[][] . 在您的Signatures属性中,尝试使用as运算符将类型转换为int[][] The Select method however returns an IEnumerable<int[]> which is not an array. 但是, Select方法返回的不是数组的IEnumerable<int[]> Use ToArray to create the array: 使用ToArray创建数组:

public int[][] Signatures
{
    get
    {
        return Nodes.Select(x => x.Signature).ToArray();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM