Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Conversion Operators

The Conversion operators in LINQ are useful in converting the type of the elements in a sequence (collection). There are three types of conversion operators: As operators (AsEnumerable and AsQueryable), To operators (ToArray, ToDictionary, ToList and ToLookup), and Casting operators (Cast and OfType).

The following table lists all the conversion operators.

MethodDescription
AsEnumerableReturns the input sequence as IEnumerable<t>
AsQueryableConverts IEnumerable<T> to IQueryable, to simulate a remote query provider
CastCoverts a non-generic collection to a generic collection (IEnumerable to IEnumerable<T>)
OfTypeFilters a collection based on a specified type
ToArrayConverts a collection to an array
ToDictionaryPuts elements into a Dictionary based on key selector function
ToListConverts collection to List<T>
ToLookupGroups elements into an Lookup<TKey,TElement>

AsEnumerable & AsQueryable

The AsEnumerable and AsQueryable methods cast or convert a source object to IEnumerable<T> or IQueryable<T> respectively.

Consider the following example: (courtesy: Jon Skeet)

Example: AsEnumerable & AsQueryable operator in C#:
class Program
{

    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("Actual type: {0}", obj.GetType().Name);
    }

    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
                new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 } ,
            };   
            
        ReportTypeProperties( studentArray);
        ReportTypeProperties(studentArray.AsEnumerable());
        ReportTypeProperties(studentArray.AsQueryable());   
    }
}
Try it
Output:
Compile-time type: Student[]
Actual type: Student[]
Compile-time type: IEnumerable`1
Actual type: Student[]
Compile-time type: IQueryable`1
Actual type: EnumerableQuery`1

As you can see in the above example AsEnumerable and AsQueryable methods convert compile time type to IEnumerable and IQueryable respectively

Visit stackoverflow for detail information on AsEnumerable and AsQueryable method.

Cast

Cast does the same thing as AsEnumerable<T>. It cast the source object into IEnumerable<T>.

Example: Cast operator in C#
class Program
{

    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("Actual type: {0}", obj.GetType().Name);
    }

    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
                new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 } ,
            };   
         
        ReportTypeProperties( studentArray);
        ReportTypeProperties(studentArray.Cast<Student>());
    }
}
Try it
Output:
Compile-time type: Student[]
Actual type: Student[]
Compile-time type: IEnumerable`1
Actual type: Student[]
Compile-time type: IEnumerable`1
Actual type: Student[]
Compile-time type: IEnumerable`1
Actual type: Student[]

studentArray.Cast<Student>() is the same as (IEnumerable<Student>)studentArray but Cast<Student>() is more readable.

To Operators: ToArray(), ToList(), ToDictionary()

As the name suggests, ToArray(), ToList(), ToDictionary() method converts a source object into an array, List or Dictionary respectively.

To operators force the execution of the query. It forces the remote query provider to execute a query and get the result from the underlying data source e.g. SQL Server database.

Example: ToArray & ToList in C#
IList<string> strList = new List<string>() { 
                                            "One", 
                                            "Two", 
                                            "Three", 
                                            "Four", 
                                            "Three" 
                                            };

string[] strArray = strList.ToArray<string>();// converts List to Array

IList<string> list = strArray.ToList<string>(); // converts array into list
Try it

ToDictionary - Converts a Generic list to a generic dictionary:

Example: ToDictionary in C#:
IList<Student> studentList = new List<Student>() { 
                    new Student() { StudentID = 1, StudentName = "John", age = 18 } ,
                    new Student() { StudentID = 2, StudentName = "Steve",  age = 21 } ,
                    new Student() { StudentID = 3, StudentName = "Bill",  age = 18 } ,
                    new Student() { StudentID = 4, StudentName = "Ram" , age = 20 } ,
                    new Student() { StudentID = 5, StudentName = "Ron" , age = 21 } 
                };

//following converts list into dictionary where StudentId is a key
IDictionary<int, Student> studentDict = 
                                studentList.ToDictionary<Student, int>(s =&gt; s.StudentID); 

foreach(var key in studentDict.Keys)
	Console.WriteLine("Key: {0}, Value: {1}", 
                                key, (studentDict[key] as Student).StudentName);
Try it
Output:
Key: 1, Value: John
Key: 2, Value: Steve
Key: 3, Value: Bill
Key: 4, Value: Ram
Key: 5, Value: Ron

The following figure shows how studentDict in the above example contains a key-value pair, where key is a StudentID and the value is Student object.

LINQ-ToDictionary Operator
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.