Using foreach

  • Thread starter Thread starter tony
  • Start date Start date
T

tony

Hello

I use foreach when I have a container of some kind for example an array or
ArrayList.

But in this case is it really possible to use foreach. In case it is how
would I write it.

for( int i = 0; i < dSMspComposition.Tables[0].Rows.Count; i++ )
compositionList.Add(dSMspComposition.Tables[0].Rows["COMP_NAME"]);


//Tony
 
you can use foreach over the datarow collection:

foreach (DataRow row in dSMspComposition.Tables[0].Rows)
{
compositionList.Add(row["COMP_NAME"]);
}
 
Tony,

You can use foreach on any object that supports IEnumerable interface or has
instance GetEnumerator method declared.
 
Stoitcho said:
You can use foreach on any object that supports IEnumerable interface or
has instance GetEnumerator method declared.

BTW I wonder why ArraySegment<T> doesn't have a GetEnumerator<T>.

Is there an easy way of foreach'ing an ArraySegment<T> or a T[] array?
 
Ole Nielsby said:
BTW I wonder why ArraySegment<T> doesn't have a GetEnumerator<T>.

Not sure. That's a bit odd.
Is there an easy way of foreach'ing an ArraySegment<T> or a T[] array?

You can certainly foreach over T[]. Here's an example:

using System;

class Foo<T>
{
T[] x;

public Foo(T[] data)
{
x = data;
foreach (T t in x)
{
Console.WriteLine(t);
}
}
}

class Test
{
static void Main()
{
new Foo<string>(new string[]{"hello", "there"});
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top