C#Linq – 无法将IEnumerable 隐式转换为List
我有一个像这样定义的List:
public List AttachmentURLS;
我正在向列表添加项目,如下所示:
instruction.AttachmentURLS = curItem.Attributes["ows_Attachments"].Value.Split(';').ToList().Where(Attachment => !String.IsNullOrEmpty(Attachment));
但我收到此错误:无法隐式将IEnumerable转换为List
我究竟做错了什么?
Where方法返回IEnumerable
。 尝试添加
.ToList()
到底如此:
instruction.AttachmentURLS = curItem.Attributes["ows_Attachments"].Value.Split(';').ToList().Where(Attachment => !String.IsNullOrEmpty(Attachment)).ToList();
像这样将.ToList()
移动到最后
instruction.AttachmentURLS = curItem .Attributes["ows_Attachments"] .Value .Split(';') .Where(Attachment => !String.IsNullOrEmpty(Attachment)) .ToList();
Where扩展方法返回IEnumerable
, Where
将在数组上工作,因此在Split
之后不需要ToList
。
.ToList()
应该是最后的。 因为在您的代码中,您先执行.ToList()
操作,然后再执行以前的状态。 Where方法返回IEnumerable。