现有数组中某些值的新数组
本文关键字:数组 新数组 | 更新日期: 2023-09-27 18:25:03
如果我得到一个数组,比如:
string[] test = new string[5] { "hello", "world", "test", "world", "world"};
我怎么能用同一个字符串"世界"组成一个新的数组呢?你之前知道有多少,这里是3?
我想的是:
string[] newArray = new string[3];
for (int i = 0; i < 5; i++)
{
if (test[i].Contains("world"))
{
newArray[i] = test[i];
}
}
问题就在这里:newArray[i] = test[i];
由于它从0迭代到4,因此会出现错误,因为newArray被限制为3。
如何解决此问题?
编辑:我需要从测试(旧数组)开始,位置1、3和4应该存储在newArray中的0、1和2。
您想要使用Linq:
var newArray = test.Where(x => x.Contains("world")).ToArray();
改用List<string>
:
List<string> newList = new List<string>();
for (int i = 0; i < 5; i++)
{
if (test[i].Contains("world"))
{
newList.Add(test[i]);
}
}
如果您以后真的需要它作为数组。。转换列表:
string[] newArray = newList.ToArray();
您对test
和newArray
使用相同的索引i
。我建议您创建另一个计数器变量并将其递增:
string[] newArray = new string[3];
int counter = 0;
for (int i = 0; i < 5; i++)
{
if (test[i].Contains("world"))
{
newArray[counter] = test[i];
counter++;
}
}
从技术上讲,这不是你的问题,但如果你想基于相同单词的数组加载数组,你可以进行
test.GroupBy(x => x).ToList();
这会给你一个列表。。根据你的测试数据,这将是
list1 - hello
list2 - world world world
list3 - test
示例使用
var lists = test.GroupBy(x => x).ToList();
foreach(var list in lists)
{
foreach(var str in list)
{
Console.WriteLine(str);
}
Console.WriteLine();
}
带有一个额外的辅助索引变量
string[] newArray = new string[3];
for (int i = 0, j = 0; i < 5; i++)
{
if (test[i].Contains("world"))
{
newArray[j++] = test[i];
if (j >= newArray.Length)
break;
}
}