C#统计List<T>字符串属性长度(返回每个属性的最大长度)
说明
导入大批量数提交List<T>时,经常会出现字符串长度错误,这段代码非常有用。
统计结果
根据属性值长度调整字段的长度。
C# 全选
/// <summary>
/// C#统计List<T>字符串属性长度(返回每个属性的最大长度)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<PropertyMaxLengthInfo> GetStringPropertyMaxLengths<T>(List<T> list)
{
var result = new List<PropertyMaxLengthInfo>();
if (list == null || list.Count == 0)
{
return result;
}
Type type = typeof(T);
// 获取所有string类型的公共属性
PropertyInfo[] stringProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(string))
.ToArray();
foreach (var prop in stringProperties)
{
int maxLength = 0;
foreach (var item in list)
{
string value = (string)prop.GetValue(item);
int currentLength = value?.Length ?? 0;
if (currentLength > maxLength)
{
maxLength = currentLength;
}
}
result.Add(new PropertyMaxLengthInfo
{
FieldName = prop.Name,
MaxLength = maxLength
});
}
return result;
}
C# 全选
public class PropertyMaxLengthInfo
{
public string FieldName { get; set; }
public int MaxLength { get; set; }
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网