使用LINQ Sum()和Where()方法:
public static int GetTotalLengthOfStringProperties(object obj)
{
Type type = obj.GetType();
IEnumerable<PropertyInfo> info = type.GetProperties();
int total = info.Where(p => p.PropertyType == typeof (String))
.Sum(pr => (((String) pr.GetValue(obj, null))
?? String.Empty).Length);
return total;
}
PS:爲了使 LINQ你已經添加using System.Linq
;
編輯:更通用的方法
/// <summary>
/// Gets a total length of all string-type properties
/// </summary>
/// <param name="obj">The given object</param>
/// <param name="anyAccessModifier">
/// A value which indicating whether non-public and static properties
/// should be counted
/// </param>
/// <returns>A total length of all string-type properties</returns>
public static int GetTotalLengthOfStringProperties(
object obj,
bool anyAccessModifier)
{
Func<PropertyInfo, Object, int> resolveLength = (p, o) =>
((((String) p.GetValue(o, null))) ?? String.Empty).Length;
Type type = obj.GetType();
IEnumerable<PropertyInfo> info = anyAccessModifier
? type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Instance | BindingFlags.Static)
: type.GetProperties();
int total = info.Where(p => p.PropertyType == typeof (String))
.Sum(pr => resolveLength(pr, obj));
return total;
}
來源
2011-10-14 09:05:12
sll
具有_hundreds_屬性的對象?聽起來你可能想考慮使用'Dictionary'代替。 –
你是指所有物業的總長度是什麼意思?他們的價值? – Rob
property.length()? – EO2