简体   繁体   中英

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

I have list of type Notification . I also have a type of 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.

when I go to create a List<NotificationWithScore> n = new List<NotificationWithScore>();

I can only assign them individually using a foreach. Is there a way to do this in Linq?

Use LINQ

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM