今天早上我来了,这似乎是一个很容易解决的问题。我想将列表的所有值写入控制台。在这种情况下,列表包含列表成员。我一直在寻找解决方案已有一段时间,但找不到。
到目前为止,我已经做到了。
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);
});
我不确定您想要什么,但是此递归解决方案可能会帮助您。我稍微作弊是因为我在寻找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()
以返回更多信息,而不仅仅是对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句