2014-11-04 1 views
2

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

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

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); 
     }); 
+0

Взгляните на http://stackoverflow.com/questions/26712142/how-to-get-all-names-and-values-of-any-object-using-reflection-and-recursion/26712208#26712208 –

ответ

0

Я не совсем уверен, что вы хотите, но это рекурсивное решение может помочь вам на вашем пути. Я немного обманул, потому что я ищу 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(), чтобы вернуть больше информации, чем просто объект.

+0

Спасибо, Мэтью! Я попробую сразу. :) – Nieksa