简体   繁体   English

C#Linq - 无法隐式转换IEnumerable <string> 列表 <string>

[英]C# Linq - Cannot implicitly convert IEnumerable<string> to List<string>

I have a List defined like this : 我有一个像这样定义的List:

public List<string> AttachmentURLS;

I am adding items to the list like this: 我正在向列表添加项目,如下所示:

instruction.AttachmentURLS = curItem.Attributes["ows_Attachments"].Value.Split(';').ToList().Where(Attachment => !String.IsNullOrEmpty(Attachment));

But I am getting this error: Cannot implicitly convert IEnumerable to List 但我收到此错误:无法隐式将IEnumerable转换为List

What am I doing wrong? 我究竟做错了什么?

The Where method returns an IEnumerable<T> . Where方法返回IEnumerable<T> Try adding 尝试添加

.ToList()

to the end like so: 到底如此:

instruction.AttachmentURLS = curItem.Attributes["ows_Attachments"]
  .Value.Split(';').ToList()
  .Where(Attachment => !String.IsNullOrEmpty(Attachment))
  .ToList();

Move the .ToList() to the end like this 像这样将.ToList()移动到最后

instruction.AttachmentURLS = curItem
    .Attributes["ows_Attachments"]
    .Value
    .Split(';')
    .Where(Attachment => !String.IsNullOrEmpty(Attachment))
    .ToList();

The Where extension method returns IEnumerable<string> and Where will work on arrays, so the ToList isn't needed after the Split . Where扩展方法返回IEnumerable<string>Where将在数组上工作,因此在Split之后不需要ToList

The .ToList() should be at last. .ToList()应该是最后的。 Because in your code you perform the .ToList() operation earlier and after that again it goes to previous state. 因为在您的代码中,您先执行.ToList()操作,然后再执行以前的状态。 The Where method returns an IEnumerable. Where方法返回IEnumerable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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