Least cost to return an one-row IEnumerable object?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a function must return an one-row IEnumerable object. Any lesser cost
way than the following code?

static IEnumerable MyUDF()
{
DataTable dt;
dt.Columns.Add("Test");
dt.Rows.Add(1);
return dt.Rows;
}
 
nick said:
I have a function must return an one-row IEnumerable object. Any lesser cost
way than the following code?

return new T[] { the_t };


or in your case:

string[] x = { "Test" };
return x;
static IEnumerable MyUDF()
{
DataTable dt;
dt.Columns.Add("Test");
dt.Rows.Add(1);
return dt.Rows;
}

That won't work, I don't think it will compile either :)
 
Helge Jensen said:
string[] x = { "Test" };
return x;

I didn't understand the question... but if this is the answer, then
maybe a neater answer would be

static IEnumerable MyUDF()
{ yield return "Test";
}
 
Lucian said:
I didn't understand the question... but if this is the answer, then
maybe a neater answer would be

static IEnumerable MyUDF()
{ yield return "Test";
}

I figured it must be C#-1, since an IEnumerable was used, not an
IEnumerable<T>.

Also yeild produces methods that return IEnumerator, not IEnumerable,
and it makes a difference, since you cannot "foreach" an IEnumerator.

A slightly more complicated solution using C#-2 and yeild would be
something like:

public class SingleItem<T>: IEnumerable<T> {
public readonly T Item;
public SingleItem(T item) { this.Item = item; }
public IEnumerator<T> GetEnumerator() { yield return Item; }
}
static IEnumerable<string> MyUDF() { return new SingleItem("Test"); }
 
Helge Jensen said:
I figured it must be C#-1, since an IEnumerable was used, not an
IEnumerable<T>.
Also yeild produces methods that return IEnumerator, not IEnumerable,

Are you sure? Here's the MSDN page about yield:

public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
 
Helge Jensen said:
I figured it must be C#-1, since an IEnumerable was used, not an
IEnumerable<T>.

Also yeild produces methods that return IEnumerator, not IEnumerable,
and it makes a difference, since you cannot "foreach" an IEnumerator.

It does any of IEnumerable,IEnumerator,IEnumerable<T>,IEnumerator<T>.
 
Back
Top