Custom OfType()-like method

Here's my version of Enumerable.OfType() method:

Copy & Paste the following codes in LinqPad. And, in LinqPad's Language dropdown > choose "C# Program" and press F5 to run:
void Main()
{

    var userprofileList = new UserProfile { FirstName = "John" , LastName = "Doe" };
    var userprofileList1 = new UserProfile { FirstName = "Juan" , LastName = "Dela Cruz" };
    var countryList = new Country{ Population= 105, City = "Cebu"};

    var arrlist = new ArrayList();
    arrlist.Add(userprofileList);
    arrlist.Add(countryList);
    arrlist.Add(userprofileList1);
    arrlist.Dump();
 
    var filteredList = arrlist.OfType<UserProfile>();
    ("OfType() result.").Dump();
    filteredList.Dump();
 
    var myFilteredList = arrlist.Cast<object>().ToList().FilterArr<UserProfile>();
    ("Custom type-filtering FilterArr() method result.").Dump();
    myFilteredList.Dump();
}

public static class Extensions
{
 public static List<X> FilterArr<X>(this IEnumerable<dynamic> source) where X : class
 {
  var filterList = source.Where(itm => itm is X).Cast<X>();
  return filterList.ToList();
 }
}

public class UserProfile
{
     public string FirstName { get;set; }
     public string LastName { get;set; }
}

public class Country
{    
     public int Population { get;set; }
     public string City { get;set; }
}


No comments:

Post a Comment