我有一个对象列表,我想将所有"null“字段更新为string.empty。
以下是代码:
public class Class1
{
public string P1 { get; set; }
public string P2 { get; set; }
public string P3 { get; set; }
}我希望有一个代码,它在所有字段中查找所有空值,并将值更改为string.empty。
static void Main(string[] args)
{
var list= new List<Class1>();
var class1 = new Class1 {P1 = "P1-1", P2 = "P2-1", P3="null"};
list.Add(class1);
var class2 = new Class1 { P1 = "P1-2", P2 = "P2-2", P3 = "null" };
list.Add(class2);
}因此,我需要找到class1.P3和class2.P3,并替换它们的值。
谢谢
发布于 2017-06-26 17:38:00
您可以编写这样一个简短的泛型函数:
private static IEnumerable<TSource> ReplaceValues<TSource>(IEnumerable<TSource> source, object oldValue,
object newValue)
{
var properties = typeof(TSource).GetProperties();
foreach (var item in source)
{
foreach (var propertyInfo in properties.Where(t => Equals(t.GetValue(item), oldValue)))
{
propertyInfo.SetValue(item, newValue);
}
yield return item;
}
}这比您的更有效,因为您的集合类型是TSource,这意味着内部的所有类型都具有相同的属性。获取和缓存这些属性将加快进程,因为您只调用Type.GetProperties()一次,而不是操作和过滤这些结果。
更新
正如下面关于Ivan Stoev的注释部分所讨论的那样,让方法只修改集合而不返回任何值会更合适:
private static void ReplaceValues<TSource>(IEnumerable<TSource> source, object oldValue,
object newValue)
{
var properties = typeof(TSource).GetProperties();
foreach (var item in source)
{
foreach (var propertyInfo in properties.Where(t => Equals(t.GetValue(item), oldValue)))
{
propertyInfo.SetValue(item, newValue);
}
}
}发布于 2017-06-26 17:23:12
它会处理好的:
static void Main(string[] args)
{
var list= new List<Class1>();
var class1 = new Class1 {P1 = "P1-1", P2 = "P2-1", P3="null"};
list.Add(class1);
var class2 = new Class1 { P1 = "P1-2", P2 = "P2-2", P3 = "null" };
list.Add(class2);
foreach (var item in list)
{
var props2 = from p in item.GetType().GetProperties()
let attr = p.GetValue(item)
where attr != null && attr.ToString() == "null"
select p;
foreach (var i in props2)
{
i.SetValue(item, string.Empty);
}
}
}最新情况::
下面是一种更有效的方法。
static void Main(string[] args)
{
var list = new List<Class1>();
var class1 = new Class1 {P1 = "P1-1", P2 = "P2-1", P3 = "null"};
list.Add(class1);
var class2 = new Class1 {P1 = "P1-2", P2 = "P2-2", P3 = "null"};
list.Add(class2);
var updatedList= ReplaceValues(list, "null", string.Empty);
}
private static IEnumerable<TSource> ReplaceValues<TSource>
(IEnumerable<TSource> source, object oldValue,
object newValue)
{
var properties = typeof(TSource).GetProperties();
var sourceToBeReplaced = source as TSource[] ?? source.ToArray();
foreach (var item in sourceToBeReplaced)
{
foreach (var propertyInfo in properties.Where(t => Equals(t.GetValue(item), oldValue)))
{
propertyInfo.SetValue(item, newValue);
}
}
return sourceToBeReplaced;
}https://stackoverflow.com/questions/44765192
复制相似问题