Получить все значения списка с его вложенными свойствами списка

Этим утром я столкнулся с проблемой, которая казалась простой для решения. Я хотел записать все значения списка в свою консоль. В этом случае список содержит членов списка. Я искал решение в течение некоторого времени, но я не мог его найти.

Я сделал это до сих пор.

tl.ForEach(tradelane =>
        {
            row = "";

            foreach(PropertyInfo pi in typeof(coTradeLane).GetProperties())
            {
                Type T = pi.PropertyType;

                if (T.IsGenericType && T.GetGenericTypeDefinition() == typeof(List<>))
                {
                    foreach(PropertyInfo piList in tradelane.GetType().GetProperties())
                    {

                            // Select the nested list and loop through each member..

                    }
                    continue;
                }

                var val = pi.GetValue(tradelane);
                if (val != null) row += val.ToString() + " \t ";
                else row += " \t \t ";
            }
            Console.WriteLine(row);
        });

person Nieksa    schedule 04.11.2014    source источник
comment
Взгляните на stackoverflow.com/questions/26712142/   -  person Ed Chapel    schedule 04.11.2014


Ответы (1)


Я не совсем уверен, чего вы хотите, но это рекурсивное решение может помочь вам на вашем пути. Я немного схитрил, потому что ищу IList, а не List<T>, чтобы упростить код.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
    // This type contains two properties.
    // One is a plain List<Double>, the other is a type that itself contains Lists.

    public sealed class Container
    {
        public List<double> Doubles { get; set; }

        public Lists Lists { get; set; }
    }

    // This type contains two Lists.

    public sealed class Lists
    {
        public List<string> Strings { get; set; }
        public List<int> Ints { get; set; }
    }

    public static class Program
    {
        private static void Main()
        {
            var lists = new Lists
            {
                Strings = new List<string> {"A", "B", "C"}, 
                Ints = new List<int> {1, 2, 3, 4, 5}
            };

            var container = new Container
            {
                Doubles = new List<double> {1.1, 2.2, 3.3, 4.4},
                Lists = lists
            };

            var items = FlattenLists(container);

            // This prints:
            //
            // 1.1
            // 2.2
            // 3.3
            // 4.4
            // A
            // B
            // C
            // 1
            // 2
            // 3
            // 4
            // 5

            foreach (var item in items)
                Console.WriteLine(item);
        }

        // This recursively looks for all IList properties in the specified object and its subproperties.
        // It returns each element of any IList that it finds.

        public static IEnumerable<object> FlattenLists(object container)
        {
            foreach (var pi in container.GetType().GetProperties().Where(p => p.GetMethod.GetParameters().Length == 0))
            {
                var prop = pi.GetValue(container);

                if (typeof(IList).IsAssignableFrom(pi.PropertyType))
                {
                    foreach (var item in (IList) prop)
                        yield return item;
                }

                foreach (var item in FlattenLists(prop))
                    yield return item;
            }
        }
    }
}

Я не уверен, насколько это полезно, поскольку вы просто получаете сглаженный список object без представления о свойстве, с которым они связаны. Однако вы можете изменить FlattenLists(), чтобы возвращать больше информации, чем просто объект.

person Matthew Watson    schedule 04.11.2014
comment
Спасибо Мэтью! Я попробую это прямо сейчас. :) - person Nieksa; 04.11.2014