简体   繁体   中英

convert a class object into another class object and then combine

Say that I have two models/classes.

public class Male
{
    public int RunNumber { get; set; }
    public string Notes { get; set; }
    public DateTime thing {get ; set;}
}

public class Female
{
    public int StopNumber { get; set; }
    public string Notes { get; set; }
    public DateTime? thing {get;set;}
}

I want a List<People> by combining List<Male> and List<Female> . Every time I look at LINQ, my brain doesn't cooperate with me. I think it's concat I'm after.

Assuming you don't want to get too fancy, and there is a reason that Male & Female have different members (no pun intended) and do not inherit a common parent, create a data transfer object and use Select to map into it.

    public class Person
    {
        public int StopNumber { get; set; }
        public string Notes { get; set; }
        public DateTime? thing { get; set; }
        public bool IsMale { get; set; }
    }

    public List<Person> Join(List<Male> males, List<Female> females)
    {
        return
            males.Select(
                n => new Person() {
                    IsMale = true, 
                    Notes = n.Notes, 
                    StopNumber = n.RunNumber, 
                    thing = n.thing} 
            ).Concat(
                     females.Select(
                         m => new Person() {
                                IsMale = false,
                                Notes = m.Notes, 
                                StopNumber = m.StopNumber, 
                                thing = m.thing})
                ).ToList();
    }

However -- if they can inherit a common Person base class and have common member names, it will make your life far easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM