比方说,我有一个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
PS,你的签名是不完全正确,变化值具有的IEnumerable的键 –
2012-08-11 09:10:15
@MAfifi - 我不明白,为什么呢? – 2012-08-11 09:13:11
您将尝试使用类型T对数组进行索引。这不起作用,因为索引器总是期望它是一个整数。看我下面的例子。 – 2012-08-11 09:25:01