How do I make my Linq to Sql class IEnumerable
-
21-08-2019 - |
Question
How do I make my Linq to Sql class IEnumerable or an object IEnumerable in C# 3.0
Solution
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...
}
}
OTHER TIPS
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.
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?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow