public class SomePropertyClass{
public string VarA{get;set;}
public string VarB{get;set;}
}
SomePropertyClass v1 = new SomePropertyClass(){VarA = "item 1"};
SomePropertyClass v2 = new SomePropertyClass(){VarB = "item 2"};
Run Code Online (Sandbox Code Playgroud)
是否可以创建第三个变量,它将具有:
v3:VarA =“项目1”,VarB =“项目2”
我的意思是,我想将对象与 linq to object 合并。
现在编辑我需要相同类型的。但将来按属性名称合并会很好。
我有一个帐户模型,其中包含用户在第 1 步中输入的许多属性。
我想将此半满模型与第 2 步半满模型合并。
编辑 2
//step 1
GlobalOnBoardingDataModel step1= (GlobalOnBoardingDataModel)HttpContext.Current.Session[SessionVariableNameStepOne];
//step 2
GlobalOnBoardingDataModel step2 = (GlobalOnBoardingDataModel)HttpContext.Current.Session[SessionVariableNameStepTwo];
class GlobalOnBoardingDataModel {
public string Email;//step 1
public string Name;//step 1
public string Phone;//step2
public string Address;//step2
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
这是 OP 问题的答案,即:
public static T Merge<T>(T target, T source)
{
typeof(T)
.GetProperties()
.Select((PropertyInfo x) => new KeyValuePair<PropertyInfo, object>(x, x.GetValue(source, null)))
.Where((KeyValuePair<PropertyInfo, object> x) => x.Value != null).ToList()
.ForEach((KeyValuePair<PropertyInfo, object> x) => x.Key.SetValue(target, x.Value, null));
//return the modified copy of Target
return target;
}
Run Code Online (Sandbox Code Playgroud)