【问题标题】:Lambda expression for foreach loops having child foreach loops(nested foreach) and change the value具有子 foreach 循环(嵌套 foreach)的 foreach 循环的 Lambda 表达式并更改值
【发布时间】:2014-05-23 06:31:21
【问题描述】:

我有两个类如下:

    public class Notification
    {
        public System.Guid NotificationId { get; set; }
        public Nullable<System.Guid> ClassId { get; set; }
        public Nullable<System.Guid> SentBy { get; set; }
        public string SenderName { get; set; }
        public Nullable<bool> Visible { get; set; }
        public string MessageText { get; set; }
        public Nullable<System.Guid> ClassViewRegId { get; set; }
        public string CreatedBy { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string LastModifiedBy { get; set; }
        public Nullable<System.DateTime> LastModifiedDate { get; set; }
        public List<MessageRecipient> Recipients { get; set; }
    }

    public partial class Recipient
    {
        public System.Guid NotificationRecipientId { get; set; }  
        public System.Guid NotificationId { get; set; }
        public string RecipientType { get; set; }
        public Nullable<System.Guid> RecipientId { get; set; }   
        public Nullable<System.Guid> ClassId { get; set; }
        public Nullable<System.Guid> ClassViewRegId { get; set; }
    }

现在我的代码有 List 有另一个列表 List。

所以我尝试检查并更改值如下:

 notify.Where(n => n.Recipients.Where(r => r.RecipientType == "Teacher").ToList().ForEach(s=>s.RecipientType="");

请任何人帮助我如何检查和更改子列表属性的值。

【问题讨论】:

    标签: c# foreach lambda nested


    【解决方案1】:

    使用简单的 foreach 循环:

    var teachers = notify.SelectMany(n => n.Recipients)
                         .Where(r => r.RecipientType == "Teacher");
    
    foreach(Recipient teacher in teachers)
        teacher.RecipientType = "";
    

    【讨论】:

    • 您好,谢谢,我需要相同的集合,只需要根据某些条件更改值。
    • @user3667751 因此教师是一个引用类型,那么通知对象内的所有教师都会被更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2021-09-24
    • 2015-07-15
    • 1970-01-01
    相关资源
    最近更新 更多