Mark
Mark

Reputation: 1035

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

Upvotes: 4

Views: 2139

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126804

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('|'));

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564333

You can do this:

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

Upvotes: 0

Related Questions