首页 > 解决方案 > 如何将值列表插入到 Enumerable 中?

问题描述

我必须查看 IEnumerable 中的第一个元素是否等于某个值,如果是,我必须将其更新为新列表

我正在尝试使用类似的东西

if (sequence.First().Equals(value))
        {

            return newValues.Prepend(sequence.Skip(1));

        }

因为我必须是最通用的,但是当我尝试测试这个调用时它只返回 null

标签: c#ienumerableenumerable

解决方案


你不能修改IEnumerable. 但是你可以使用这种方法:

// your sample:
IEnumerable<int> sequence = new[] {2, 5, 1};
int value = 2;
IEnumerable<int> newValues = new[] {1, 2, 3};

if (sequence.First() == value)
    return newValues.Concat(sequence.Skip(1)).ToList()
else
    return sequence.ToList();

推荐阅读