我有一个对象的数组/列表/集合/等。出于示例目的,我们假设它只是一个字符串数组/列表/集合/等。C#将元素拆分为多个元素
我想遍历数组并根据特定条件拆分某些元素。这全部由我的对象处理。因此,一旦我有要分割的对象索引,分割对象的标准方法是什么,然后按顺序将它重新插入到原始数组中。我会尽量表现出我的意思是使用的是什么的字符串数组:
string[] str = { "this is an element", "this is another|element", "and the last element"};
List<string> new = new List<string>();
for (int i = 0; i < str.Length; i++)
{
if (str[i].Contains("|")
{
new.AddRange(str[i].Split("|"));
}
else
{
new.Add(str[i]);
}
}
//new = { "this is an element", "this is another", "element", "and the last element"};
此代码的工作和一切,但有一个更好的方式来做到这一点?有没有一个已知的设计模式,像一个就地数组拆分?
我有同样的想法,但要符合OP的代码,它应该是ToList()... – 2010-10-22 01:11:08
考虑到这是在他的问题的样本,我不认为它很重要。但是我添加了ToList()调用,并将其作为投影。 – 2010-10-22 01:13:26
谢谢,完美。我并不十分关心ToList的东西。 – Mark 2010-10-22 02:14:27