C# Linq - Cannot implicitly convert IEnumerable

2020-07-01 06:55发布

I have a List defined like this :

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

What am I doing wrong?

标签: c# linq
3条回答
混吃等死
2楼-- · 2020-07-01 07:34

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.

查看更多
够拽才男人
3楼-- · 2020-07-01 07:38

The Where method returns an 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();
查看更多
疯言疯语
4楼-- · 2020-07-01 07:47

Move the .ToList() to the end like this

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.

查看更多
登录 后发表回答