2

I have following codes (I am a beginner);

string myVar = "abcd";
var myQuery = from x in myVar select x;     
MessageBox.Show( string.Join("\n", myQuery));

I'd like to have the result like this;

1 a
2 b
3 c
4 d

Some hints please.

Thanks.

3
  • Jason, Is this a school work / homework issue? If so, I'd like to recommend that you first do it without linq, so that you understand what's going on behind the scenes. Commented Feb 19, 2016 at 15:40
  • @Joe ..Thanks for good tip. I can handle it without LINQ. Now I'm at chap 8 "LINQ" of Albabari brothers. (I found the second argument at Pg.385 but it lacks "it is Fluent-syntax only"). Commented Feb 19, 2016 at 15:57
  • "Local query" means Fluent syntax ? Commented Feb 19, 2016 at 16:01

1 Answer 1

8

You should use Select operator overload which accepts index of item. (unfortunately it's not available in query syntax):

String.Concat(myVar.Select((ch,i) => $"{i + 1} {ch}\n"))

Update: @Mattew correctly noticed that this code will add extra \n at the end. If it's not good, then you should use String.Join instead. Also consider to use Environment.NewLine thus for windows platform new line string is \r\n:

String.Join(Environment.NewLine, myVar.Select((ch,i) => $"{i + 1} {ch}"))
Sign up to request clarification or add additional context in comments.

8 Comments

Wow. so simple. Second argument... OK. I will check it out right now. Thanks.
I added number 1 "(i + 1)". Works like a charm. Thanks again.
As a note this would add an extra line fee at the end compared to OPs example.
@MatthewWhited nice catch, then String.Join is better here. I just tried to make code more compact. Thanks)
string.Join("\n", myVar.Select((ch,i) => $"{i + 1} {ch}")) would resolve the extra line fee (if it matters ;)
|

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.