C#Linq - 无法将IEnumerable 隐式转换为List

时间:2022-11-25 16:31:02

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?

我究竟做错了什么?

3 个解决方案

#1


33  

The Where method returns an IEnumerable<T>. Try adding

Where方法返回IEnumerable 。尝试添加

.ToList()

to the end like so:

到底如此:

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

#2


7  

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 ,Where将在数组上工作,因此在Split之后不需要ToList。

#3


2  

The .ToList() should be at last. Because in your code you perform the .ToList() operation earlier and after that again it goes to previous state. The Where method returns an IEnumerable.

.ToList()应该是最后的。因为在您的代码中,您先执行.ToList()操作,然后再执行以前的状态。 Where方法返回IEnumerable。

#1


33  

The Where method returns an IEnumerable<T>. Try adding

Where方法返回IEnumerable 。尝试添加

.ToList()

to the end like so:

到底如此:

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

#2


7  

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 ,Where将在数组上工作,因此在Split之后不需要ToList。

#3


2  

The .ToList() should be at last. Because in your code you perform the .ToList() operation earlier and after that again it goes to previous state. The Where method returns an IEnumerable.

.ToList()应该是最后的。因为在您的代码中,您先执行.ToList()操作,然后再执行以前的状态。 Where方法返回IEnumerable。