Zeusoflightning125
Zeusoflightning125

Reputation: 170

Looping as an expression

I come across things where this would be useful rather often, and if it exists I want to know about it. I'm not really sure how to explain it to search for it, but it's basically a one line loop statement- similar to a lambada. This isn't the best example (it's a simple solution without this), but it's what was on my mind when I decided to finally ask this question. But this is the kind of thing I'm talking about.

(The following is what I'm thinking of looks like. I'm asking if something similar exists)

In my current situation, I am converting a string into a byte array to write to a stream. I want to be able to do this to create the byte array:

    byte[] data = String ==> (int i; Convert.ToByte(String[i]))

Where i is the number in the string based on it's length, and the next line is the output for item.

Upvotes: 0

Views: 72

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

  1. You should read about LINQ.

  2. Your code can be written as:

    var String = "some string";
    byte[] data = String.Select(x => Convert.ToByte(x)).ToArray();
    

    or even with method group:

    byte[] data = String.Select(Convert.ToByte).ToArray();
    

Upvotes: 6

Related Questions