如果使用linq子列表为空,则无法转换带有子列表的对象列表?

时间:2019-01-02 19:04:14

标签: c# list linq

我有这段代码将一个对象列表转换为另一个对象列表。该代码可以正常工作,但如果Messages属性为空,则不能。我以为将Any与?:运算符配合使用可解决此问题,但还没有,但是我得到了Null Reference Exception。

var TemporaryMessageGroupList = MyList.Select(x => new MessageGroupModel()
        {
            Id = x.Id,
            Name = x.Name,
            DisplayPicture = x.DisplayPicture,
            LastMessage = x.LastMessage,
            Archived = x.Archived,
            Messages = (x.Messages.Any() ? x.Messages.Select(y => new MessageModel()
            {
                Id = y.Id,
                CreatorId = y.CreatorId,
                Content = y.Content,
                TimeSent = y.TimeSent,
                GroupId = y.GroupId,
                HasAttachment = y.HasAttachment,
                AttachmentImage = y.AttachmentImage,
                IsRead = y.IsRead
            }).ToList() : new List<MessageModel>()),
            Members = x.Members.Select(c => new UserModel()
            {
                Id = c.Id,
                FullName = c.FullName,
                DisplayPicture = c.DisplayPicture
            }).ToList()
        }).ToList();

我只希望能够将一个对象列表转换为上面的对象列表,如果有人知道另一种方法来解决该问题,请告诉我,谢谢!

2 个答案:

答案 0 :(得分:1)

如果Any为空,则在Messages上调用Messages会产生上述异常,相反:

 Messages = x.Messages?.Select(y => new MessageModel()
            {
                Id = y.Id,
                CreatorId = y.CreatorId,
                Content = y.Content,
                TimeSent = y.TimeSent,
                GroupId = y.GroupId,
                HasAttachment = y.HasAttachment,
                AttachmentImage = y.AttachmentImage,
                IsRead = y.IsRead
            }).ToList() ?? new List<MessageModel>(),
  • 如果使用null,则使用“空传播”运算符?.阻止在Select上调用Messages
  • 然后在??为空的情况下,使用“空合并”运算符Messages生成一个新的空列表。

答案 1 :(得分:0)

您可以尝试这样,确保x.Messages不为NULL,并且如果为空则首选为空集合,还请确保Messages的属性对于原始对象不为null或在接收时为空对象:

Messages = (x.Messages?.Where(msg => msg != null).Select(y => new 
MessageModel() {}).ToList()