繁体   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