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"};
是否可以创建具有以下内容的第三个变量:
v3:VarA =“item 1”,VarB =“item 2”
我的意思是,我想将对象与linq合并到对象。
修改
现在我需要来自同一类型。但是通过属性名称合并将来会很好。
我有一个帐户模型,其中包含许多用户在步骤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
}
}
感谢
答案 0 :(得分:3)
你的意思是这样的......一个Merge方法,从匹配的属性中取出哪个值不为空?
public class SomePropertyClass{
public string VarA{get;set;}
public string VarB{get;set;}
public SomePropertyClass Merge (SomePropertyClass other)
{
return new SomePropertyClass
{ VarA = this.VarA ?? other.VarA,
VarB = this.VarB ?? other.VarB
};
}
如果您想要一个适用于任何类的解决方案,您需要使用反射来查找所有属性,然后复制丢失的属性。 }
答案 1 :(得分:3)
以下是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;
}
答案 2 :(得分:2)
以下是使用反射实现此目的的方法:
public class SomePropertyClass
{
public string VarA { get; set; }
public string VarB { get; set; }
}
static class Program
{
static void Main(string[] args)
{
SomePropertyClass v1 = new SomePropertyClass() { VarA = "item 1" };
SomePropertyClass v2 = new SomePropertyClass() { VarB = "item 2" };
var yo = v1.Combine(v2);
}
static public IEnumerable<object> Combine<T, U>(this T one, U two)
{
var properties1 = one.GetType().GetProperties().Where(p => p.CanRead && p.GetValue(one, null) != null).Select(p => p.GetValue(one, null));
var properties2 = two.GetType().GetProperties().Where(p => p.CanRead && p.GetValue(two, null) != null).Select(p => p.GetValue(two, null));
return new List<object>(properties1.Concat(properties2));
}
}