开发者

C# Splitting Element Into Multiple Elements

I have an array/list/collection/etc of objects. For sample purposes, lets assume it is just a string array/list/collection/etc.

I want to iterate through the array and split certain elements based on c开发者_StackOverflow中文版ertain criteria. This is all handled by my object. So once I have the object index that I want to split, what is the standard way of splitting the object and then reinserting it back into the original array in order. I'll try and demonstrate what I mean using a string array:

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"};

This code works and everything, but is there a better way to do this? Is there a known design pattern for this; for like an inplace array split?


For this particular example, you could utilize SelectMany to get your new array.

string[] array = { "this is an element", "this is another|element", "and the last element" };
string[] newArray = array.SelectMany(s => s.Split('|')).ToArray();
// or List<string> newList = array.SelectMany(s => s.Split('|')).ToList();
// or IEnumerable<string> projection = array.SelectMany(s => s.Split('|'));


You can do this:

List<string> newStr = str.SelectMany(s => s.Split('|')).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜