SexyMF SexyMF - 4 years ago 186
C# Question

C# Merge 2 objects of the same with linq 2 object

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"};


Is it possible to create a third variable that will have:

v3: VarA = "item 1",VarB = "item 2"

I mean, I want to merge objects with linq to object.

Edit

for now i need from the same type. but it would be nice in the future to merge by property name.

I have an account model with a lot of properties that the user input in step 1.

I want to merge this half full model with step 2 half full model.

Edit 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
}
}


thanks

Answer Source

Here's a way to accomplish this using reflection:

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));
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download