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
。
より高度なシナリオでは、複数の引数を使用してソースを置き換える必要がある場合もあります。とは a から来ている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