簡體   English   中英

將一個類對象轉換為另一個類對象,然后合並

[英]convert a class object into another class object and then combine

假設我有兩個模型/類。

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

我想要一個List<People>組合List<Male>List<Female> 每次看LINQ,我的大腦都不配合。 我認為這是我追求的連續性。

假設你不想太花哨,並且有一個原因,男性和女性有不同的成員(沒有雙關語)並且不繼承共同的父級,創建一個數據傳輸對象並使用 Select 映射到它。

    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();
    }

但是——如果它們可以繼承一個公共的 Person 基類並具有公共的成員名稱,那么它會讓您的生活變得更加輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM