假设我有一个 int 数组:
var source = new int[] { 1, 2, 3, 4, 5 };
我想使用这些数组替换它的一部分:
var fromArray = new int[] { 1, 2 };
var toArray = new int[] { 11, 12 };
我需要使用上面的数组产生的输出是:11, 12, 3, 4, 5
.
在更高级的场景中,我可能还需要使用多个参数替换源。认为fromArray
并且toArray
来自Dictionary<int[], int[]>
:
IEnumerable<T> Replace(IEnumerable<T> source,
IDictionary<IEnumerable<T>, IEnumerable<T>> values)
{
// "values" parameter holds the pairs that I want to replace.
// "source" can be `IList<T>` instead of `IEnumerable<T> if an indexer
// is needed but I prefer `IEnumerable<T>`.
}
我怎样才能做到这一点?
编辑:项目的顺序很重要。认为它像String.Replace
; 如果 的全部内容fromArray
不存在source
(例如,如果源只有1
并且不存在2
),则该方法不应尝试替换它。一个例子:
var source = new int[] { 1, 2, 3, 4, 5, 6 };
var dict = new Dictionary<int[], int[]>();
// Should work, since 1 and 2 are consecutive in the source.
dict[new int[] { 1, 2 }] = new int[] { 11, 12 };
// There is no sequence that consists of 4 and 6, so the method should ignore it.
dict[new int[] { 4, 6 }] = new int[] { 13, 14 };
// Should work.
dict[new int[] { 5, 6 }] = new int[] { 15, 16 };
Replace(source, dict); // Output should be: 11, 12, 3, 4, 15, 16