替换 IEnumerable<string> 中的特定项目

Replace a specific item in IEnumerable<string>

我是 C# 的新手,正在处理 IEnumerable。我想替换 IEnumerable 中的特定项目。例如。

IEnumerable<string> m_oEnum = new string[] {"abc","def","ghi", "abcdef"};

我只想将字符串 "abc" 替换为 "abc-test",而不是更改 "abcdef"。

m_oEnum  = m_oEnum.Select(s => s == "abc" ? "abc-test" : s).ToArray();

要建立 Tim Schmelter 的答案,您将像这样使用现有代码实现,请注意您不需要将变量声明为 IEnumerable<string>

var m_oEnum = new string[] { "abc", "def", "ghi", "abcdef" };
m_oEnum = m_oEnum.Select(s => s == "abc" ? "abc-test" : s).ToArray();

如果您打算更新数组中的特定值,并且您会知道要更新的项目的索引:

var itemIndex = 0
var m_oEnum = new string[] { "abc", "def", "ghi", "abcdef" };
m_oEnum[itemIndex] = "abc-test"

否则,其他答案将达到相同的效果。请注意,源数组变量实际上不会那样改变。

试试

m_oEnum.ToList()[0]="abc-test";

为什么不使用扩展方法?

考虑以下代码:

        var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
        // Replaces the first occurance and returns the index
        var index = intArray.Replace(1, 0);
        // {0, 0, 1, 2, 3, 4}; index=1

        var stringList = new List<string> { "a", "a", "c", "d"};
        stringList.ReplaceAll("a", "b");
        // {"b", "b", "c", "d"};

        var intEnum = intArray.Select(x => x);
        intEnum = intEnum.Replace(0, 1);
        // {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
  • 没有重复的代码
  • 无需键入长 linq 表达式
  • 无需额外使用

源代码:

namespace System.Collections.Generic
{
    public static class Extensions
    {
        public static int Replace<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            var index = source.IndexOf(oldValue);
            if (index != -1)
                source[index] = newValue;
            return index;
        }

        public static void ReplaceAll<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            int index = -1;
            do
            {
                index = source.IndexOf(oldValue);
                if (index != -1)
                    source[index] = newValue;
            } while (index != -1);
        }


        public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x);
        }
    }
}

添加了前两个方法来更改引用类型的对象。当然,你也可以只对所有类型使用第三种方法。

另一个问题的相同答案:https://whosebug.com/posts/38728879/edit