'For In's in C#?

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
HarvesteR
Posts: 65
Joined: Mon May 10, 2010 1:13 pm UTC

'For In's in C#?

Postby HarvesteR » Tue Jan 18, 2011 10:22 pm UTC

Long story short, I'm kissing Javascript (in Unity3D) goodbye, and welcoming the awesomeness that is C# on Visual Studio :D

The change was not at all as bad as I expected... syntax-wise it's pretty much the same as Java, with some generics thrown in...
One thing got to me though...

I tried a 'for in' loop today, and what I got was a squiggly red line suggesting there was no such thing... there is a 'for each' loop, I'm sure, since VS offers a handy snippet for that... but no 'for in's? (I find that strange, since 'for in's are actually more manual-labor-ish than 'for each's)

Or is there, and I'm just n00bing my way around a new language? (I hope so)

All hail Intellisense 8)

Cheers
The next sentence is the truth. - The previous sentence is a lie.

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: 'For In's in C#?

Postby Sc4Freak » Tue Jan 18, 2011 10:33 pm UTC

Is there something that "for-in" does that "foreach" doesn't?

Code: Select all

void PrintStrings(List<string> text)
{
   foreach(String s in text)
   {
      Console.WriteLine(s);
   }
}

User avatar
HarvesteR
Posts: 65
Joined: Mon May 10, 2010 1:13 pm UTC

Re: 'For In's in C#?

Postby HarvesteR » Tue Jan 18, 2011 10:42 pm UTC

It's useful when you need the key as well as the value... 'for in' returns the key (index), while 'for each' returns the value.

Code: Select all


MyObjectWithProperties obj1;
MyObjectWithProperties obj2;

// here's a part where both objects get treated differently and might end up with different values

// comparing properties
for (SomeDataType o in obj1)
{
     if (obj1[o] != obj2[o])
          // do something
}




That works in Javascript and friends... I'm really hoping C# will support that too

Cheers
The next sentence is the truth. - The previous sentence is a lie.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: 'For In's in C#?

Postby Xeio » Tue Jan 18, 2011 10:53 pm UTC

No, it won't do that directly, but most dictionary types have a .Keys property you can iterate over. But for a straight array, you'd have to keep track of indexes yourself (short of something fancy with Linq).

EDIT: Yea, on second thought, you might as well just use a for loop for an array (or non-keyed list).
Last edited by Xeio on Tue Jan 18, 2011 11:05 pm UTC, edited 3 times in total.

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: 'For In's in C#?

Postby Sc4Freak » Tue Jan 18, 2011 10:58 pm UTC

HarvesteR wrote:It's useful when you need the key as well as the value... 'for in' returns the key (index), while 'for each' returns the value.

Code: Select all


MyObjectWithProperties obj1;
MyObjectWithProperties obj2;

// here's a part where both objects get treated differently and might end up with different values

// comparing properties
for (SomeDataType o in obj1)
{
     if (obj1[o] != obj2[o])
          // do something
}




That works in Javascript and friends... I'm really hoping C# will support that too

Cheers

If you're iterating over a list (eg. List<T>) type, your indices are integers. In that case, you'd use a simple for loop:

Code: Select all

for(int i = 0; i < list.Count; ++i) {}


If you're iterating over a dictionary type (eg. Dictionary<K, V>), foreach gives you a KeyValuePair:

Code: Select all

Dictionary<string, Object> dict;
foreach(KeyValuePair<string, Object> kvp in dict)
{
    Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
}

User avatar
HarvesteR
Posts: 65
Joined: Mon May 10, 2010 1:13 pm UTC

Re: 'For In's in C#?

Postby HarvesteR » Tue Jan 18, 2011 11:19 pm UTC

Sc4Freak wrote:If you're iterating over a dictionary type (eg. Dictionary<K, V>), foreach gives you a KeyValuePair:


Aha! That's what I was looking for!!

Thanks!!!!

Cheers
The next sentence is the truth. - The previous sentence is a lie.

User avatar
Emu*
Posts: 689
Joined: Mon Apr 28, 2008 9:47 am UTC
Location: Cardiff, UK
Contact:

Re: 'For In's in C#?

Postby Emu* » Wed Jan 19, 2011 8:50 am UTC

This is one of the few times PHP beats "disciplined" languages:

foreach (array_expression as $key => $value){

}


I miss it.
Cosmologicon wrote:Emu* implemented a naive east-first strategy and ran it for an hour, producing results that rivaled many sophisticated strategies, visiting 614 cells. For this, Emu* is awarded Best Deterministic Algorithm!

sigmaman
Posts: 12
Joined: Thu Dec 04, 2008 12:05 am UTC

Re: 'For In's in C#?

Postby sigmaman » Wed Jan 19, 2011 1:30 pm UTC

My personal favorite is Python:

Code: Select all

for variable in iterator:
     do_stuff()


Although... Java isn't that bad:

Code: Select all

for(Type value: arraytype){}

User avatar
Zamfir
I built a novelty castle, the irony was lost on some.
Posts: 7606
Joined: Wed Aug 27, 2008 2:43 pm UTC
Location: Nederland

Re: 'For In's in C#?

Postby Zamfir » Wed Jan 19, 2011 2:17 pm UTC

sigmaman wrote:My personal favorite is Python:

Code: Select all

for variable in iterator:
     do_stuff()


Although... Java isn't that bad:

Code: Select all

for(Type value: arraytype){}

How are those really different from for each? I think c# even has something like iterators, although I never used it.

sigmaman
Posts: 12
Joined: Thu Dec 04, 2008 12:05 am UTC

Re: 'For In's in C#?

Postby sigmaman » Wed Jan 19, 2011 3:15 pm UTC

I was mostly concerned with syntax, so they really aren't different from foreach. A response to how PHP is "better" than other languages.

EDIT:

I just realize I kinda misread the PHP thing, and so I propose the following in python:

Code: Select all

for k,v in dict.items():
     do_stuff()


Which is what the PHP is actually trying to do. Sadly there is no real equivalence in Java, although you could probably get something similar in a lot more lines of code.

User avatar
HarvesteR
Posts: 65
Joined: Mon May 10, 2010 1:13 pm UTC

Re: 'For In's in C#?

Postby HarvesteR » Wed Jan 19, 2011 5:45 pm UTC

I think we all feel the best way is the one we already knew... for me it's AS3:

Code: Select all

for (var i:int in obj)
{
    doStuffTo( obj[i] );
}

for each (var o:Object in obj)
{
    doStuffTo( o );
 
}



Cheers
The next sentence is the truth. - The previous sentence is a lie.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: 'For In's in C#?

Postby Xeio » Wed Jan 19, 2011 7:50 pm UTC

I think that's pretty horrifying that the behavior can change depending on the type you try to pull out... what if you're storing an array of ints? :shock:

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: 'For In's in C#?

Postby TheChewanater » Wed Jan 19, 2011 8:04 pm UTC

Code: Select all

(define my-list (list "Scheme " "for-" "each " "is " "neat. " 87))

(for-
each display my-list) 
Last edited by TheChewanater on Thu Jan 20, 2011 1:56 am UTC, edited 1 time in total.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

squareroot
Posts: 548
Joined: Tue Jan 12, 2010 1:04 am UTC
Contact:

Re: 'For In's in C#?

Postby squareroot » Thu Jan 20, 2011 1:39 am UTC

HarvesteR wrote:I think we all feel the best way is the one we already knew...


Heh, not me. Java's way of doing this pisses me off (even though I've programmed in Java a longer/tons more than PHP, whose syntax I vastly prefer). :x
Last edited by squareroot on Thu Jan 20, 2011 3:52 am UTC, edited 1 time in total.
<signature content="" style="tag:html;" overused meta />
Good fucking job Will Yu, you found me - __ -

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: 'For In's in C#?

Postby phlip » Thu Jan 20, 2011 2:45 am UTC

Xeio wrote:I think that's pretty horrifying that the behavior can change depending on the type you try to pull out... what if you're storing an array of ints? :shock:

It's not the type, it's the syntax... JavaScript is the same (since AS and JS are both ECMAScript):

Code: Select all

a = [1,2,5]
for (i in a) print(i);
0
1
2
for each (i in a) print(i);
1
2
5


Personally, I think Python is the most flexible of the procedural languages... since you can loop over dict.items() or enumerate(list) if you need the key and value. And other options exist if you just want one or the other, or something else entirely (like map or filter).

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: 'For In's in C#?

Postby Xeio » Thu Jan 20, 2011 1:06 pm UTC

phlip wrote:
Xeio wrote:I think that's pretty horrifying that the behavior can change depending on the type you try to pull out... what if you're storing an array of ints? :shock:

It's not the type, it's the syntax... JavaScript is the same (since AS and JS are both ECMAScript)
Oops, I totally missed that "each". *facepalm*

It would be nice to have index variable in a foreach loop occasionally though for C#. Though I'd end up having to use a for anyway at work because we have a lot of 1-based arrays (0 indicates something other than an index, since we also have types that are singles).

User avatar
RebeccaRGB
Posts: 336
Joined: Sat Mar 06, 2010 7:36 am UTC
Location: Lesbians Love Bluetooth
Contact:

Re: 'For In's in C#?

Postby RebeccaRGB » Thu Jan 20, 2011 6:45 pm UTC

sigmaman wrote:

Code: Select all

for k,v in dict.items():
     do_stuff()

Which is what the PHP is actually trying to do. Sadly there is no real equivalence in Java, although you could probably get something similar in a lot more lines of code.


Code: Select all

for (Map.Entry<K,V> e : dict.entrySet()) {
    do_stuff(e.getKey(), e.getValue());
}


You were saying?
Stephen Hawking: Great. The entire universe was destroyed.
Fry: Destroyed? Then where are we now?
Al Gore: I don't know. But I can darn well tell you where we're not—the universe!

User avatar
Emu*
Posts: 689
Joined: Mon Apr 28, 2008 9:47 am UTC
Location: Cardiff, UK
Contact:

Re: 'For In's in C#?

Postby Emu* » Fri Jan 21, 2011 8:09 am UTC

Not exactly elegant, is it?
Cosmologicon wrote:Emu* implemented a naive east-first strategy and ran it for an hour, producing results that rivaled many sophisticated strategies, visiting 614 cells. For this, Emu* is awarded Best Deterministic Algorithm!

User avatar
RebeccaRGB
Posts: 336
Joined: Sat Mar 06, 2010 7:36 am UTC
Location: Lesbians Love Bluetooth
Contact:

Re: 'For In's in C#?

Postby RebeccaRGB » Fri Jan 21, 2011 8:57 am UTC

Not that much worse than C#, really. But far from "no real equivalent" in "a lot more lines of code."
Stephen Hawking: Great. The entire universe was destroyed.
Fry: Destroyed? Then where are we now?
Al Gore: I don't know. But I can darn well tell you where we're not—the universe!

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: 'For In's in C#?

Postby Xeio » Fri Jan 21, 2011 2:01 pm UTC

Well, I dunno about comparable to C# in that specific case (especially if you can use >=3.0 for var). If you have to use the longhand KeyValuePair<type1, type2> it is close to the same (Properties for syntactic sugar are still awesome though).

Code: Select all

foreach(var e in dict){
    DoStuff(e.Key, e.Value);
}

User avatar
Zamfir
I built a novelty castle, the irony was lost on some.
Posts: 7606
Joined: Wed Aug 27, 2008 2:43 pm UTC
Location: Nederland

Re: 'For In's in C#?

Postby Zamfir » Fri Jan 21, 2011 3:00 pm UTC

Xeio wrote:Well, I dunno about comparable to C# in that specific case (especially if you can use >=3.0 for var). If you have to use the longhand KeyValuePair<type1, type2> it is close to the same (Properties for syntactic sugar are still awesome though).

Code: Select all

foreach(var e in dict){
    DoStuff(e.Key, e.Value);
}

yeah, var makes c# code sometimes as close to Python as you can get without losing strong typing.

User avatar
WarDaft
Posts: 1583
Joined: Thu Jul 30, 2009 3:16 pm UTC

Re: 'For In's in C#?

Postby WarDaft » Fri Jan 21, 2011 8:26 pm UTC

I definitely definitely disagree with the first one you learn being the one you like best...

Code: Select all

keys dict
...from Haskell is pretty appealing, but definitely wasn't the first form of 'for..in' I encountered. Heck, I haven't even had cause to use it more than once or twice yet.
All Shadow priest spells that deal Fire damage now appear green.
Big freaky cereal boxes of death.

User avatar
HarvesteR
Posts: 65
Joined: Mon May 10, 2010 1:13 pm UTC

Re: 'For In's in C#?

Postby HarvesteR » Sat Jan 22, 2011 2:11 am UTC

WarDaft wrote:I definitely definitely disagree with the first one you learn being the one you like best...


Yeah, I reckon that might not be the case for everyone...

The first language I learned was ActonScript 2, which I now find horrible... I really found myself with AS3, though... something about it's javascript-like syntax, but explicit typing makes for an excellent coding experience :)

Python is nice too... it has some features that really should be in all languages, like an 'else' block for when 'for' loops end without breaking... but, same as Javascript, no explicit data-typing is horrible... it sounds nice at first, but then when you have a function that needs a specific object to work... the horror begins :roll:

I didn't kow C# had 'var'... I will look into that!!

Cheers
The next sentence is the truth. - The previous sentence is a lie.

sigmaman
Posts: 12
Joined: Thu Dec 04, 2008 12:05 am UTC

Re: 'For In's in C#?

Postby sigmaman » Sat Jan 22, 2011 12:49 pm UTC

RebeccaRGB wrote:
sigmaman wrote:

Code: Select all

for k,v in dict.items():
     do_stuff()

Which is what the PHP is actually trying to do. Sadly there is no real equivalence in Java, although you could probably get something similar in a lot more lines of code.


Code: Select all

for (Map.Entry<K,V> e : dict.entrySet()) {
    do_stuff(e.getKey(), e.getValue());
}


You were saying?


I'm glad I was wrong :D

Next time I'm working in Java I'll be sure to look into this :)

User avatar
Yakk
Poster with most posts but no title.
Posts: 11129
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: 'For In's in C#?

Postby Yakk » Sat Jan 22, 2011 4:18 pm UTC

For completeness sake, the C++0x version:

Code: Select all

for( auto& x: container ) {
  x = 7;
}

(C++0x is not in the wild yet.)

Map type containers return std::pair<Key, Value>, so you can access their keys via x.first and values via x.second.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 11 guests