How do I make my Linq to Sql class IEnumerable or an object IEnumerable in C# 3.0
+2
A:
To make an object Enumerable in C# you would implement the IEnumerable interface
public class Widget{}
public class WidgetCollection : IEnumerable<Widget>
{
public IEnumerator<Widget> GetEnumerator()
{
throw new NotImplementedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
As for the second part of your question, I am not sure what you are asking about or trying to do.
JoshBerke
2009-05-14 14:59:20
A:
I'm not sure what you mean by "make my Linq to SQL class IEnumerable". However, in your controller (assuming ASP.NET MVC)...
WidgetDataContext dataContext = new WidgetDataContext();
var data = dataContext.Widgets.OrderBy(x => x.name);
return View(data);
In this case, the view will be able to simply cast the data
object (called Model
in the view) as an IEnumerable<Widget>
and can foreach its way through it.
Does this (with Josh's answer above) the question?
Andrew Flanagan
2009-05-14 15:01:53
A:
If you are talking about the LinqToSql generated classes then you would do it in the partial class
public partial class YourLinqToSqlClass : IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
//Implement...
}
}
J.13.L
2009-05-14 15:03:10