C # - Advanced foreach statements?

I currently have:

string settings = "setting1:value1;setting2:value2"; string[] pair; foreach(string setting in settings.Split(';')) { pair = setting.Split(':'); MessageBox.Show(pair[0] + ":" + pair[1]); } 

I would do something more line by line:

 string settings = "setting1:value1;setting2:value2"; foreach (string[] pair in string setting.Split(':') in settings.Split(';')) { MessageBox.Show(pair[0] + ":" + pair[1]); } 

The two words in seem a little ridiculous, but I think something like this will be possible and very simple, I just don't know how to do it.

So is this possible?

+4
source share
4 answers

I'm not sure this is more readable, but you asked for it, and I think it looks cool; -)

 string settings = "setting1:value1;setting2:value2"; foreach(var pair in settings.Split(';').Select(str => str.Split(':'))) { MessageBox.Show(pair[0] + ":" + pair[1]); } 

(I did not compile it, so I'm sorry for the syntax errors)

+8
source

As an alternative to the other posted answers, you can also use the LINQ syntax:

 string settings = "setting1:value1;setting2:value2"; foreach(string[] pair in from setting in settings.Split(';') select setting.Split(':')) { MessageBox.Show(pair[0] + ":" + pair[1]); } 
+7
source
 foreach (string[] pair in settings.Split(';').Select(setting => setting.Split(':'))) { MessageBox.Show(pair[0] + ":" + pair[1]); } 
+1
source
 foreach (string settingstr in settings.Split(';')) { string[] setval = settingstr.Split(':'); string setting = setval[0]; string val = setval[1]; } 
0
source

Source: https://habr.com/ru/post/1388856/


All Articles