0

Is there a way in Linq to take each element in my string[] and assign each element to a square Multi-Dimensional(2D) array by its row. Meaning, 2D[0,i], where i increments by 1 assigning 1D[i] there. Note, 1D array is guaranteed to be same length as width of 2D array. Also, my 2D array accessor is limited to only a class indexer, so my class indexer looks like this, CLASS[r,c].

Here is how I'm creating my 1D array: lineRead.Split(" ", StringSplitOptions.RemoveEmptyEntries);

In sudo code, this is what I want to achieve.

lineRead.Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(e => CLASS[r,c] = e);

I'm terrible with Linq and I feel like there should be a way to do this, obviously I don't know what I'm doing with Linq here... Lol Any ideas, any help? Thanks

2

1 Answer 1

1

Assuming r is constant (0, since you don't mention in your post), here is one way of doing it:

string lineRead = "apple mango orange grape";
int i = 0;
lineRead.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)
.ToList()
.ForEach(item => { CLASS[0, i++] = item; });

Sample Output:

CLASS[0,0] = "apple"

CLASS[0,1] = "mango"

CLASS[0,2] = "orange"

CLASS[0,3] = "grape"

Although quite frankly, a good old for loop would do just as well:

string lineRead = "apple mango orange grape";
var values = lineRead.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < values.Length; i++)
{
    CLASS[0,i] = values[i];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this does help a ton. I ended up going with a loop, but I might refactor into a Linq statement, because your solution is so elegant. What do you think about performance of the two?
@MatthewJett: I am glad I was able to help. Performance is probably around the same for both. I personally prefer more readable code. Good luck!

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.