4

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 certain 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?

2 Answers 2

3

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('|'));
Sign up to request clarification or add additional context in comments.

4 Comments

Given that it was a sample in his question, I did not consider it important. But I've added the ToList() call as well as just leaving it as a projection.
Thanks, perfect. I'm not really concerned about the ToList stuff as an fyi.
+1 @Mark: By the way it's not a good idea to name your variable as "new" since it's a keyword in C#.
Yeah good call. Just for the example. I'm pretty sure you can't use new as a variable name.
0

You can do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.