[英]C# - Split Array by Another Array
我有一个字符串数组,我想被另一个数组分割(由第二个数组中的每个项目)。
string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" };
string[] array2 = { "item2", "item5" };
结果为string[][] or List<string[]>
results[0] = { "item1" }
results[1] = { "item2", "item3", "item4" }
results[2] = { "item5", "item6" }
还有应该在下一个数组之前添加拆分的项目。 例如。 item2 拆分 results[0] 和 results[1] 并在 result[1] 前面使用。
提示:可能类似于在for
循环 function 中使用IndexOf()
或Insert()
我用字符串试过这个。 但我不知道如何处理数组。
string str = "item1,item2,item3,item4,item5,item6";
string[] array = str.Split(new string[] { "item2","item5" }, StringSplitOptions.None);
我试图在谷歌中找到这个问题,但到目前为止还没有找到。 只有我发现如何拆分成块(意思是每个数组中的项目数)而不是另一个项目(特别是多个项目)。
所以你想要一种“拆分”方法,通过在第二个集合中提供拆分索引将一个集合拆分为多个? 您可以使用以下扩展方法,该方法将Queue<T>
( FIFO ) 用于拆分项目。 它非常灵活,您可以将它与每种类型一起使用,并且您可以选择提供比较器。 例如,如果您想以不区分大小写的方式进行比较,请提供StringComparer.CurrentCultureIgnoreCase
:
public static class EnumerableExtensions
{
public static IList<IList<T>> SplitOnItems<T>(this IEnumerable<T> seqeuenceToSplit, IEnumerable<T> splitOnItems, IEqualityComparer<T> comparer = null)
{
if(comparer == null) comparer = EqualityComparer<T>.Default;
Queue<T> queue = new Queue<T>(splitOnItems);
if(queue.Count == 0)
{
return new IList<T>[]{new List<T>(seqeuenceToSplit)};
}
T nextSplitOnItem = queue.Dequeue();
List<T> nextBatch = new List<T>();
IList<IList<T>> resultList = new List<IList<T>>();
bool takeRemaining = false;
foreach(T item in seqeuenceToSplit)
{
if(!takeRemaining && comparer.Equals(item, nextSplitOnItem))
{
resultList.Add(nextBatch);
nextBatch = new List<T> { item };
if (queue.Count > 0)
{
nextSplitOnItem = queue.Dequeue();
}
else
{
takeRemaining = true;
}
}
else
{
nextBatch.Add(item);
}
}
if(nextBatch.Any())
resultList.Add(nextBatch);
return resultList;
}
}
用法:
string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" };
string[] array2 = { "item2", "item5" };
IList<IList<string>> splittedItems = array1.SplitOnItems(array2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.