.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

Why IEnumerator and IEnumerable?

Posted By:      Posted Date: October 07, 2010    Points: 0   Category :.NET Framework


I am very new to the .NEt Framework and don't really know much of the history behind it.

One question I have is related to IEnumerator and IEnumerable interface classes. Why did the team opt for two classes rather then one?

One reason could be that the IEnumerable's GetEnumerator was not implemented in the original design and the developers did not want to break existing code, but I don't think that this is the correct reason.

Thanks and Regards.


View Complete Post

More Related Resource Links

Ienumerable,ienumerator and iterator Interface in c#

how I used Ienumerable and ienumerator and itreator interface in c# with Wcf I want To used Through Class. I want To used Through C# Plz Give Me A good Example.   Thanks Neha    

IEnumerable.Except incorrectly removes duplicates

IEnumerable.Except is expected to receive a second IEnumerable with the elements to be removed from the first. But when the first collection contains duplicates, those are removed too, despite not being present on the second. Check in the following example that 2.3 appears twice on numbers1 but only once on the output. double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 }; double[] numbers2 = { 2.2 }; IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) Console.WriteLine(number); /* This code produces the following output: 2 2.1 2.3 2.4 2.5 */

Serializing objects which implement IEnumerable<>

Hi, I'm trying for long time to serialize an object which contains an object which implements IEnumerable<>. The last object also contains an object which implements IEnumerable<>. The objects strucutre is as followed: [Serializable] public class A { public B _b {get; set; } } [Serializable] public class B : IEnumerable<C> { public List<C> c_items {get; set;} public void Add (C obj){} } [Serializable] public class C : IEnumerable<D> { public List<D> d_items {get; set;} public void Add (D obj){} } [Serializable] public class D { public int Key {get; set;} public int Value {get; set;} } In the code line: A obj = new A(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); I'm getting the exception: unable to generate temporary class (result=1), error CS0030: Cannot convert type 'C' to type 'D'... When I remove the IEnumerable implementation from one of B or C, the serialization works. What as I getting wrong? Any help would be appreciated!

IEnumerable instead of IList or Collection

hi,Just wondering and see what your opinions are.I usually pass around the layers either a Custom Collection<T> or a Custom ListBase<T>:IList ..I was now wandering if instead of return from a Data Access Layer or biz layer one of those is better to actually just return an IEnumerable<T>.Shall I drop returning all those LIst<T> Collection<T> and use IEnumerable<T> instead?Would that be more flexible?Thanks for any suggestionsThanks for your help

There is no ViewData item of type 'IEnumerable' that has the key 'Carrera'.

When running the HttpGet action, it works fine. But when I run the HttpPost action, I recieve the error in the title. Can anyone help me out? Is it because the HttpPost doesn't have a ViewData declared? Thanks for the help.[HttpGet] public ActionResult Crear() { CarreraRepository carreraRepository = new CarreraRepository(); var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre); var carrerasList = new SelectList(carreras, "ID", "Nombre"); ViewData["Carreras"] = carrerasList; Materia materia = new Materia(); return View(materia); } [HttpPost] public ActionResult Crear(Materia materia, FormCollection values) { if (ModelState.IsValid) { repo.Add(materia); repo.Save(); return RedirectToAction("Index"); } return View(materia); }

Only a single enumeration is supported by this IEnumerable.

I've only seen a few other posts on the internet about this error message, and none of them seem to give an answer that's relevant to Silverlight asynchronous code. I have a data service operation, I call it from a Silverlight client. I know the service operation is returning the desired data, because I have tested the code in a synchronous aspx page load and browsed it with the debugger. However, whether I have the service operation method return an IQueryable or an IEnumerable, I can't iterate through the results in the Silverlight client code - I receive the error in the title of this post. I can't do a foreach, I can't do a for loop, I can't do a ToList, they all give that error. private void on_oppquery(IAsyncResult result) { /*Use dispatcher to ensure that the asynch call returns in the correct thread*/ Dispatcher.BeginInvoke(() => { IEnumerable<opportunity> response = null; try { /*Since this is the first page, we get back the query*/ var query = result.AsyncState as DataContext; /*Get the response of the query*/ response = query.EndExecute<opportunity>(result); /*Enumeration executes the query*/ //THIS BREAKS //response.ToList<opportunity>(); //THIS BREAKS //foreach (opportunity o

How to change the behaviour of an IEnumerator of a SortedList

Hi, The GetEnumerator() method of a sorted list return an IEnumerator whose "Current" property give a DictionaryEntry object. However I would like to create a IEnumerator class that give me back just the "Key" not a DictionaryEntry object. Here is the code I wrote, but it is not working. Can anybody help me? I get This error : Enumeration has not started or has already finished at this line of code:     dictionaryEntry = (DictionaryEntry)_sortedList.GetEnumerator().Current;      public class NetSortedListEnum : IEnumerator     {         SortedList _sortedList;         public NetSortedListEnum(SortedList sortedList) {             _sortedList = sortedList;         }         public bool MoveNext()         {             return _sortedList.GetEnumerator().MoveNext();                     }         public void Reset()         {           

IEnumerable Type Casting

Hello Everyone,  The following line is giving me an InvalidCastException when trying to convert to IEnumerable type, even though I have implemented IEnumerable interface.  Return New CountryInfo(CountryCodes(i), CountryNames(i)) (also in bold below)Imports System Imports Gaia.WebWidgets.HtmlFormatting Imports System.Collections.Generic Imports System.Globalization Public Class CountryInfo Implements IEnumerable Property Name As String Property Code As String Public Sub New(ByVal code As String, ByVal name As String) _Code = code _Name = name End Sub Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return CType(Me, IEnumerator) End Function Public Class SearchResult Private ReadOnly _countries As List(Of CountryInfo) Private ReadOnly _query As String Friend Sub New(ByVal countries As List(Of CountryInfo), ByVal query As String) _countries = countries _query = query End Sub Public ReadOnly Property IsEmpty As Boolean Get Return _countries.Count = 0 End Get End Property Public ReadOnly Property Countries As List(Of CountryInfo) Get Return _countries End Get End Property Public Function Bui

TraceListenerCollection is cleared when looping over IEnumerable

I have the following code in a class in a WPF application: In the constructor: foreach( var traceSource in AvailableSources.ToArray() ) traceSource.Listeners.Add( _listener ); Trace.AutoFlush = true; The AvailableSources property: /// <summary> /// Gets the available sources. /// </summary> /// <value>The available sources.</value> public IEnumerable<TraceSource> AvailableSources { get { yield return TraceSources.Network; // app-specific tracesource yield return TraceSources.Persistence; // app-specific tracesource yield return TraceSources.Gui; // app-specific tracesource PresentationTraceSources.Refresh(); yield return PresentationTraceSources.DataBindingSource;  // WPF tracesource yield return PresentationTraceSources.RoutedEventSource;  // WPF tracesource } } If I doesn't use ToArray() on the property AvailableSources in the foreach loop, the Listeners collection will have zero listeners. If I step through the foreach loop, I will at the end (but before hitting the first line of code outside the loop) have 1 listener in each TraceSource' Listeners collection. When I hit the first line after the loop, I get Listeners.Count = 0 on each tracesource. I've used the immediate window in VS.Net to get the current count of the listeners collection and also verified that the hash code of each tracesource instance

IEnumerator GetEnumerable Collection and VB6 Compatibility

Hello, I've successfully implemented a collection using ArrayList in C# VS2008 using Com Interop that VB6 (and VBA apps) can see. The For .. Each construct also works in VB6. However, there are still two tasks that I can't complete 1. How can I implement the method as _NewEnum() instead of GetEnumerator()? When I use [DispId(-4)] IEnumerator _NewEnum(), it is not marked in the TLB with the DispId that I chose, but an autogenerated one. 2. If I stay with GetEnumerator, and also implement on the side _NewEnum, how can I hide "GetEnumerator" from VB6 intellisense? Specifically, I'm not sure what attribute my C# method needs to have so that the method in the TLB is marked as "hidden". My current interface looks like: [Guid("6407AD48-9855-4678-8C90-5AF86A6ACD17")] [ComVisible(true)] public interface IFields { [DispId(-4)] IEnumerator GetEnumerator(); [DispId(1)] [Description("Add a new Name/Email to the collection")] IField Add(string Name, string Email); }  The generated IDL as viewed by OleViewer looks like: interface IFields : IDispatch { [id(0xfffffffc)] HRESULT GetEnumerator([out, retval] IEnumVARIANT** pRetVal); [id(0x00000001), helpstring("Add a new Name/Email to the collection")] HRESULT Add( [in] BSTR Name, [in] BSTR Email, [out,


I want to complete the following code .... what goes after orderby in IEnumerable.
What is the meaning of creating an object for IEnumerable...........
    public IEnumerable<int> GetDistinctValuesSorted()
                List<int> _distinctvalues = cls_list_integers._integerlist.Distinct().ToList<int>();
                IEnumerable<int> _orderedsequence = _distinctvalues.OrderBy(
                return _orderedsequence;


IEnumerable - anyone help out with this syntax?



I have a string which is stored as a cookie.

The string is made up of the following data:

int userId

DateTime expiryDate

A user can have a number of these, so I store them like this "userId,expiryDate$userId,expiryDate"

When I retrieve the cookie value, I then split the string and add it to a list

The list is List<OpenReviews> openReviews,  which contains the two variables above.

I use the following piece of code to split the string:

string[][] reviews = value.Split( '$' ).Select( f => f.Split( ',' ) ).ToArray();

As you can see it goes to an array which I then have to iterate through to add it back into my list.  All of which seems extremely long winded.

I believe I can use the code above to put it into an IEnumerable<IEnumerable<string>> format.  The problem is I don't know how to then get it into my List<OpenReviews>

I'm therefore looking at getting the split string into my OpensReviews list as efficiently as possible.

Anyone help?

Convert IList to datatable Error "Only a single enumeration is supported by this IEnumerable."



I am working in WCF Data service, in client side i am returning result as IEnumerable as below.

IEnumerable<MTSR> SearchResult = context1.Execute<MTSR>(new Uri(url));

i am converting this enumerable to datatable as below.

public static DataTable ToDataTable<T>(IList<T> data)

            PropertyDescriptorCollection props =
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            object[] values = new object[props

WCF and ADO.NET entity framework - Convert IEnumerable to Datatable



We are using WCF and ADO.NET entity framework in our ASP.NET 4.0 application.  we are using Entity Framework in our WCF service to execute a storedprocedure and return the results.

        public List<Cs_MT> GetSearchResult(string emailId, string localTitle, string colorGrouping)
            MTEntities db = new MTEntities();
            var query = db.SearchResult(emailId, localTitle, colorGrouping);
            List<Cs_MT> searchList = query.ToList<Cs_MT>();
            return searchList;

We are calling the WCF service from our client application and get the results as IEnumerable

IEnumerable<GetSearchResult_ByEmail_Result> SearchResult = dsContext.Execute<GetSearchResult_ByEmail_Result>(new Uri(url)); 

I want to loop through the records and form

The cost of using .AsQueryable() on an IEnumerable collection

Can anyone tell me the associated cost of using .AsQueryable on an IEnumerable collection? The documentation says it "Converts an IEnumerable to an IQueryable .", but what does that mean exactly? Is e.g. the memory footprint doubled?



ListBox.ItemsSource binding to IEnumerable



I've got a problem with binding the ListBox.ItemsSource to  a custom class implementing IEnumerable<t>.

Next is a simplified code implementing ViewModel.


 class ViewModel : System.ComponentModel.INotifyPropertyChanged
  DataCollection data = new DataCollection();

  public IEnumerable<Data> ItemsCollection // ListBox is not updated
    return data; 

  public IEnumerable<Data> ItemsCollection // Works well
    return new List<Data>(data);

 class DataCollection : IEnumerable<Data>{}

 class Data{}


This is my xaml code.


<ListBox ItemsSource="{Binding Path=ItemsCollection}"/>


If in the "ItemsCollection" property of my ViewModel I just return my object implementing IEnumerable ListBox items are not updated.

If I return new List created from my object everything works well.


Help: How to create a list(Ienumerable) using loop



I needed to modify the code(The test method part especially) present in the link ( http://blogs.msdn.com/b/lucabol/archive/2007/12/17/bisection-based-xirr-implementation-in-c.aspx)

Instead of Hard Coding the values for cash and date(under Test methods, for object such as cfs), I want to use a loop, which depending on the two arrays of cashflows and dates, that I am receiving, creates the object (cfs) insteasd.

So, right now the cfs is hardcoded something like( as can be seen in the link)

  IEnumerable<CashFlow> cfs = new CashFlow[] {
                new CashFlow(-10000, new DateTime(2008,1,1)),
                new CashFlow(2750, new DateTime(2008,3,1)),
                new CashFlow(4250, new DateTime(2008,10,30)),
                new CashFlow(3250, new DateTime(2009,2,15)),
                new CashFlow(2750, new DateTime(2009,4,1))

I want to do something like

IEnumerable<Cashflow> cfs = new Cashflow[5];

for (int j = 0; j < 5; j++)

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend