我有一个方法可以修剪第一层中的所有字符串。
public static IEnumerable<T> Trim<T>(this IEnumerable<T> collection)
{
foreach (var item in collection)
{
var stringProperties = item.GetType().GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach (var stringProperty in stringProperties)
{
var currentValue = (string)stringProperty.GetValue(item, null);
if (currentValue != null)
stringProperty.SetValue(item, currentValue.Trim(), null);
}
}
return collection;
}
但如果我的属性是一个列表,我需要在该列表中的所有字符串属性中应用 trim 功能,有人可以帮助我吗?
string
是不可变的。 - juharrforeach
结尾处使用yield return item
来使你的方法变为惰性方法,或者将其更改为接受类似于ICollection<T>
的东西。当前状态下,当调用时它将迭代IEnumerable<T>
并返回相同的IEnumerable<T>
,如果底层类型是像List<T>
这样的东西,那么这是可以的,但它可能是一个每次迭代都会生成其项的序列,这意味着你将失去所有更改。 - juharrList<List<List<List<string>>>>
,应该使用多少层深度? - Fabjan