今天早上我突然想到这似乎是一个很容易解决的问题。 我想将列表的所有值写入我的控制台。 在这种情况下,列表包含列表成员。一段时间以来,我一直在寻找解决方案,但找不到。
我已经做到了。
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()
返回更多信息,而不仅仅是对象。
关于c# - 获取 List 及其嵌套列表属性的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26731226/