简体   繁体   English

将列表的项分配给相同类型但具有添加属性的新列表

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

I have list of type Notification .我有类型Notification列表。 I also have a type of NotificationWithScore .我也有一种NotificationWithScore类型。

Notification With Score looks like:带有分数的通知看起来像:

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

I want to create a new list of type NotificationWithScore using the existing notification list I already have and provide a default score of 0.我想使用现有的通知列表创建一个NotificationWithScore类型的新列表,并提供默认分数 0。

when I go to create a List<NotificationWithScore> n = new List<NotificationWithScore>();当我去创建一个List<NotificationWithScore> n = new List<NotificationWithScore>();

I can only assign them individually using a foreach.我只能使用 foreach 单独分配它们。 Is there a way to do this in Linq?有没有办法在 Linq 中做到这一点?

Use 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