views:

306

answers:

3

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
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
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