mowwwalker
mowwwalker

Reputation: 17334

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 something more along the lines of:

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

The two in keywords seem a bit ridiculous, but I would think something like this would be possible and very easy, I just don't know how.

So, is it possible?

Upvotes: 4

Views: 1295

Answers (4)

escargot agile
escargot agile

Reputation: 22379

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 haven't compiled it, so I'm sorry if there are syntax errors)

Upvotes: 8

user743382
user743382

Reputation:

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]);
}

Upvotes: 7

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25909

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

Upvotes: 1

craig1231
craig1231

Reputation: 3867

foreach (string settingstr in settings.Split(';'))
{
    string[] setval = settingstr.Split(':');
    string setting = setval[0];
    string val = setval[1];
}

Upvotes: 0

Related Questions