簡體   English   中英

將列表的項分配給相同類型但具有添加屬性的新列表

[英]assigning items of a list to a new list of the same type but with an added property

我有類型Notification列表。 我也有一種NotificationWithScore類型。

帶有分數的通知看起來像:

public class NotificationWithScore
    {
        public Notification Notification { get; set; }
        public int Score { get; set; }
    }

我想使用現有的通知列表創建一個NotificationWithScore類型的新列表,並提供默認分數 0。

當我去創建一個List<NotificationWithScore> n = new List<NotificationWithScore>();

我只能使用 foreach 單獨分配它們。 有沒有辦法在 Linq 中做到這一點?

使用 LINQ

List<NotificationWithScore> AddScore(List<Notification> list)
{
    return list.Select(n => new NotificationWithScore { Notification = n, Score = 0 }).ToList();
}

暫無
暫無

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

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