IEnumerable is an interface.
It
is returned from query expressions.
It
implements the GetEnumerator method.
It
enables the facility to use foreach-loop.
It
permits the use of extension methods in the System.Linq namespace.
ToList
and ToArray conversion is possible to an IEnumerable instance.
In the following example the Display method accepts a list of names as
arguments and displays them in the Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Display(new List<string>
{ "Anu", "James", "Sam" });
}
static void Display(IEnumerable<string>
names)
{
foreach
(string
value in names)
Console.WriteLine(value);
}
}
The same
example is modified to accept a list of array values as arguments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IEnuExample1;
class Program
{
static void Main()
{
string[]
names = new string[] { "Anu", "James",
"Sam" };
Display(names);
}
static void Display(IEnumerable<string>
namesArg)
{
foreach
(string
value in namesArg)
Console.WriteLine(value);
}
}
The following
example convert object data into a List
instance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnumEx2
{
class Program
{
static void Main()
{
//
//
Use this input string[] array.
//
... Convert it to a List with the ToList extension.
//
string[] array = new string[]
{
"Anu", "James",
"Sam"
};
List<string>
list = array.ToList();
//
//
Display the list.
//
foreach (string value in list)
{
Console.WriteLine(value);
}
}
}
}
The following
example sorts names using the LINQ syntax and displays these sorted elements in
an array variable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnumExample3
{
class Program
{
static
void
Main()
{
//
// Use this input string[] array.
// ... Convert it to a List with the ToList
extension.
//
string[]
array = new string[]
{
"James", "Sam",
"Anu"
};
//
Use query expression on array.
//
var query = from element in array
orderby
element
select
element;
Console.WriteLine(array.Count());
string[]
array2 = query.ToArray();
//
// Display array.
//
foreach
(string
value in array2)
{
Console.WriteLine(value);
}
}
}
}