LINQ in C# - Examples - Conversion Operators (Cast, OfType) and AsEnumerable, DefaultIfEmpty

  • The conversion operators provide a simple and convenient way of converting sequences to other collection types.

Cast

  • The Cast operator is used to cast every element of an input sequence to an output sequence of the specified type. 
  • Fundamentally, Cast() is implemented like this:
public IEnumerable<T> Cast<T>(this IEnumerable source)
{
foreach(object o in source)
yield return (T) o;
}
  • As you can see from the implementation of Cast(), first in cast every element of the sequence as object o, as object as the base type of all the types in C#, then it simply try to cast the object type to corresponding type using explicit casting (T) o, if this casting fails it will throw InvalidCastException.
  • So while casting of non-generic collection holding same type of object, then only we can use Cast() operator
  • Example 1
object[] ItemsSet1 = new object[]{ "01", "02", "03"};

            string[] AfterCasting = ItemsSet1.Cast<string>().ToArray();
           
            foreach (var item in AfterCasting)
                Console.WriteLine(item);
//Output
01
02
03
  • Example 2
 ArrayList ItemsSet1 = new ArrayList{ 4, 3, 2, 1};

            List<int> AfterCasting = ItemsSet1.Cast<int>().ToList();
           
            foreach (var item in AfterCasting)
                Console.WriteLine(item);
//Output
4
3
2
1

OfType

  • If a non-generic collection contains different types of objects and we want to extract only one type of object from the collection then we can use OfType.
  • For understanding how OfType works, refer the implementation below.
public IEnumerable<T> OfType<T>(this IEnumerable source)
{
foreach(object o in source)
if(o is T)
yield return (T) o;
}
  • Example 1
ArrayList ItemsSet1 = new ArrayList{ "Raja", 3, "Ravi", 1};

            List<int> AfterCasting = ItemsSet1.OfType<int>().ToList();
           
            foreach (var item in AfterCasting)
                Console.WriteLine(item);
//Output
3
1

AsEnumerable

  • The AsEnumerable operator simply causes its input sequence of type IEnumerable to be returned as type IEnumerable
  • Example - this example is using Query Expression Syntax
Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");

var custs = from c in db.Customers
                  where c.City == "Rio de Janeiro"
                  select c;
foreach (var cust in custs)
           Console.WriteLine("{0}", cust.CompanyName);

DefaultIfEmpty

  • Refer the example below
List<string> StudentNames = new List<string> { "Ram", "Raja", "Ravi"};

            //In below statement the assumption is that, there is atleast one name with length >5
            //so the method first will return the first name with length >5
            //But there is no name, so exception will be thrown at runtime of Type System.InvalidOperationException:

            string FoundName = StudentNames.Where(x => x.Length > 5).DefaultIfEmpty().First();
            if(FoundName!=null)
                Console.WriteLine("found Name {0}", FoundName);
            else
                Console.WriteLine("No name found");
  • Fix is using DefaultIfEmpty Example 1 - returns default value of type string is null
List<string> StudentNames = new List<string> { "Ram", "Raja", "Ravi"};           

string FoundName = StudentNames.Where(x => x.Length > 5).DefaultIfEmpty().First();

            if(FoundName!=null)
                Console.WriteLine("found Name {0}", FoundName);
            else
                Console.WriteLine("No name found");

//Output
No name found
  • Fix is using DefaultIfEmpty Example 2 with Default Specified
 List<string> StudentNames = new List<string> { "Ram", "Raja", "Ravi"};
           
 string FoundName = StudentNames.Where(x => x.Length > 5).
DefaultIfEmpty("Akshara").First();
     
            Console.WriteLine("found Name {0}", FoundName);
//Output
found Name Akshara

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...