EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

IEnumerable C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » IEnumerable C#

IEnumerable C#

Introduction to IEnumerable C#

IEnumerable is an interface, which defines only one method, GetEnumerator. The method returns an IEnumerator interface. This interface is used to iterate lists or collection of classes that are of anonymous types. It contains the System. Collections.Generic namespace. It is used to work with LINQ query expression as well. This allows only a read only access to the collection, then a collection that inherits the main collection can be iterated using a for-each loop. The IEnumerable interface is the base interface for all non-generic lists. There are four extension methods of IEnumerable interfaces. They are AsParallel(), AsQueryable(), Cast<TResult>(), OfType<TResult>(). This article will explain in detail about the IEnumerable interface along with various examples.

Syntax of IEnumerable C#

The syntax of the IEnumerable is as follows:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

public interface IEnumerable

The collection is iterated using the movenext() and reset() methods.

Extension Methods in IEnumerable C#

Below are the methods of IEnumerable C#:

  • Cast<TResult>(IEnumerable): The non-generic collection of the IEnumerable interface is converted to the specified type mentioned.
  • OfType<TResult>(IEnumerable): The elements of the IEnumerable are filtered based on the type mentioned.
  • AsParallel(IEnumerable): This is used to enable the running of parallel queries.
  • AsQueryable(IEnumerable): This is used to convert IEnumerable interface to IQueryable interface.

Examples to Implement of IEnumerable C#

Below are the example of IEnumerable C#:

Example #1

Code:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
namespace TestEg
{
class Test : IEnumerable
{
Test[] coll = null;
int Fi = 0;
public String Fname { get; set; }
public string lastnme { get; set; }
public Test()
{
coll = new Test[10];
}
public void Add(Test item)
{
coll[Fi] = item;
Fi++;
}
// IEnumerable Member
public IEnumeratorGetEnumerator()
{
foreach (object o in coll)
{
if(o == null)
{
break;
}
yield return o;
}
}
}
class Program
{
public static void Main(String[] args)
{
Test tobj = new Test();
tobj.Fname = "viki";
tobj.lastnme = "krish";
Test tobj1 = new Test();
tobj1.Fname = "nand";
tobj1.lastnme = "viki";
Test myList = new Test();
Test tobj2 = new Test();
tobj2.Fname = "vyapini";
tobj2.lastnme = "viki";
Test tobj3 = new Test();
tobj3.Fname = "tai";
tobj3.lastnme = "viki";
myList.Add(tobj);
myList.Add(tobj1);
myList.Add(tobj2);
myList.Add(tobj3);
foreach (Test obj in myList)
{
Console.WriteLine("Fname:" +  obj.Fname + "\t\t" + "lastnme :" + obj.lastnme);
}
Console.ReadLine();
}
}
}

Output:

IEnumerable C# example 1

Example #2

Code:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
public class test : IEnumerable
{
public string Student1 { get; set; }
public string Student2 { get; set; }
public string Student3 { get; set; }
public IEnumeratorGetEnumerator() { return new testEnumerator(this); }
}
public class testEnumerator : IEnumerator
{
public testEnumerator(test ts) { _ts = ts; }
private test _ts;
private int _index = 0;
public void Reset() { _index = 0; Current = null; }
public object Current { get; private set; }
public bool MoveNext()
{
_index++;
/**/ if (_index == 1) { Current = _ts.Student1; return true; }
else if (_index == 2) { Current = _ts.Student2; return true; }
else if (_index == 3) { Current = _ts.Student3; return true; }
else return false;
}
}
class Program
{
public static void Main(String[] args)
{
varts = new test() {Student1 = "vignesh", Student2 = "nandhini", Student3 = "vyapini"};
foreach (string name in ts)
{
Console.WriteLine(name);
}
}
}

Output:

IEnumerable C# example 2

Example #3

Code:

using System.Linq;
using System.Collections.Generic;
using System;
namespace TestOper
{
public class testclass
{
public inteid { get; set; }
public string ename { get; set; }
public double salary { get; set; }
}
class Program
{
public static void Main()
{
List<testclass>listtestclasss = new List<testclass>
{
new testclass { eid= 1001, ename = "viki", salary = 1000 },
new testclass { eid= 1002, ename = "nandhini", salary = 600 },
new testclass { eid= 1003, ename = "vyapinin", salary = 10000 }
};
Dictionary<int, testclass>empdic = listtestclasss.ToDictionary(x =>x.eid);
foreach (KeyValuePair<int, testclass>kvp in empdic)
{
Console.WriteLine("eid" + kvp.Key + " ename : " + kvp.Value.ename + ", salary: " + kvp.Value.salary);
}
Console.ReadKey();
}
}
}

Output:

Key Value Pair example 3

Example #4

Code:

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = new int[] {
1,13,51,75
};
Dictionary<int, bool>dic =
numbers.ToDictionary(v => v, v => true);
foreach (KeyValuePair<int, bool> pair in dic)
{
Console.WriteLine(pair);
}
List<string> names = new List<string>()
{
"vignesh","jagan","nyan","ravi","siva","sethu"
};
var result = names.ToDictionary(x => x, x => true);
if (result.ContainsKey("jagan"))
{
Console.WriteLine("name exists");
}
}
}

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Output:

IEnumerable C# example 4

Example #5

Code:

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<emp>sl = new List<emp>()
{
new emp(){empid = 1, empname = "James", empgender = "Male",eage=60},
new emp(){empid = 2, empname = "Sara", empgender = "Female",eage=90},
new emp(){empid = 3, empname = "Steve", empgender = "Male",eage=80},
new emp(){empid = 4, empname = "Pam", empgender = "Female",eage=70},
new emp(){empid = 5, empname = "James", empgender = "Male",eage=60},
new emp(){empid = 6, empname = "Sara", empgender = "Female",eage=50},
new emp(){empid = 7, empname = "Steve", empgender = "Male",eage=20},
new emp(){empid = 8, empname = "Pam", empgender = "Female",eage=40}
};
IQueryable<emp>iq = sl.AsQueryable()
.Where(t =>t.eage> 40);
foreach (varemp in iq)
{
Console.WriteLine( $"empid : {emp.empid}  empname : {emp.empname} eage : {emp.eage} empgender : {emp.empgender} ");
}
Console.ReadKey();
}
}
public class emp
{
public intempid { get; set; }
public string empname { get; set; }
public string empgender { get; set; }
public inteage { get; set; }
}
}

Output:

foreach loop example 5

Conclusion

Thus, the article explained in detail about IEnumerable in C#. It also explained the various methods like GetEnumerator and other extended methods that are associated with IEnumerable like AsParallel(), AsQueryable(), Cast<TResult>(), OfType<TResult>() in detail. It also demonstrated with example the use of current, next, and reset methods. To learn more in detail it would be advisable to write sample programs and practice them.

Recommended Articles

This is a guide to IEnumerable C#. Here we discuss a brief overview on IEnumerable C# and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –

  1. Method Overloading in C#
  2. Static Constructor Works in C#
  3. Polymorphism in C#
  4. Private in C#

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More