如何替换集合中的一系列项目,使用其他集合? [英] How to replace a sequence of items in a collection, using other collections?
问题描述
假设我有一个int数组:
Let's say I have an int array:
var source = new int[] { 1, 2, 3, 4, 5 };
我想使用这些数组替换它的一部分:
I want to replace a portion of it using these arrays:
var fromArray = new int[] { 1, 2 };
var toArray = new int[] { 11, 12 };
我需要使用上面的数组产生的输出是: 11,12 ,3,4,5
。
The output I need to produce using the arrays above is: 11, 12, 3, 4, 5
.
在更高级的场景中,我可能还需要使用多个参数替换源。认为 fromArray
和 toArray
来自字典< int [],int [] >
:
In a more advanced scenario, I may also need to replace the source using multiple arguments. Think that fromArray
and toArray
are coming from a 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
),该方法不应尝试替换它。例如:
The order of the items is important. Think it like String.Replace
; if the whole content of the fromArray
doesn't exist in source
(if the source has only 1
and not 2
, for example) the method shouldn't try to replace it. An example:
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
推荐答案
确定,这里是基于您编辑的问题的答案。完全未经测试当然。
OK, here's an answer based on your edited question. Completely untested of course.
static IEnumerable<T> Replace<T>(IEnumerable<T> source, IDictionary<IEnumerable<T>, IEnumerable<T>> values)
{
foreach (var kvp in values)
source = ReplaceOne(source, kvp.Key, kvp.Value);
return source;
}
static IEnumerable<T> ReplaceOne<T>(IEnumerable<T> source, IEnumerable<T> fromSeq, IEnumerable<T> toSeq)
{
var sArr = source.ToArray();
int replLength = fromSeq.Count();
if (replLength != toSeq.Count())
throw new NotSupportedException();
for (int idx = 0; idx <= sArr.Length - replLength; idx++)
{
var testSeq = Enumerable.Range(idx, replLength).Select(i => sArr[i]);
if (testSeq.SequenceEqual(fromSeq))
{
Array.Copy(toSeq.ToArray(), 0, sArr, idx, replLength);
idx += replLength - 1;
}
}
return sArr;
}
这篇关于如何替换集合中的一系列项目,使用其他集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!