[英]merge two lists of same type in c#
我有兩個相同類型的列表,如下所示:
public class ParentTutorCountModel
{
/// <summary>
/// Gets or sets Location
/// </summary>
public string Location { get; set; }
/// <summary>
/// Gets or sets Location
/// </summary>
public int ParentCount { get; set; }
/// <summary>
/// Gets or sets Location
/// </summary>
public int TutorCount { get; set; }
}
我有兩種方法可以按位置返回父母和導師的數量,這意味着位置在兩者中都很常見,我得到的結果如下:
父計數結果
Location TutorCount ParentCount
Loc1 0 1
Loca2 0 5
Loca3 0 3
和TutorCountResult
Location TutorCount ParentCount
Loc1 4 0
Loca2 2 0
Loc4 2 0
我想要得到的是:
Location TutorCount ParentCount
Loc1 4 1
Loca2 2 5
Loca3 0 3
Loc4 2 0
我試過 Union,加入但沒有得到想要的結果。 請幫我。
謝謝@Rob,這對我有用
var result = parentCount.Concat(tutorCount).GroupBy(r => r.Location).Select(r => new
{
Location = r.Key,
TutorCount = r.Sum(rr => rr.TutorCount),
ParentCount = r.Sum(rr => rr.ParentCount)
});
首先連接兩個列表,group by 和 sum。
我正在使用 union 並獲得相同的輸出。
var resultq1 = from a in parentCount.Union(tutorCount)
group a by a.Location into temp
select new
{
Location = temp.Key,
TutorCount = temp.Sum(rr => Convert.ToInt32(rr.TutorCount)),
ParentCount = temp.Sum(rr => Convert.ToInt32(rr.ParentCount)),
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.