tags:

views:

43

answers:

2

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?

+3  A: 

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('|'));
Anthony Pegram
I had the same idea, but to match the OP's code, it should be ToList()...
Reed Copsey
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.
Anthony Pegram
Thanks, perfect. I'm not really concerned about the ToList stuff as an fyi.
Mark
+1 @Mark: By the way it's not a good idea to name your variable as "new" since it's a keyword in C#.
Danny Chen
Yeah good call. Just for the example. I'm pretty sure you can't use new as a variable name.
Mark
A: 

You can do this:

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