using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public class EmployeeDto
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EmployeeEntity
{
public int Id { get; set; }
public string FullName { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<object> o = new List<object>();
o.Add(new EmployeeDto { Id = 1, Name = "Bob" });
o.Add(null);
o.Add(new EmployeeDto { Id = 2, Name = "Foo" });
o.Add(null);
o.AddRange(AddMilionOfEmployees());
Stopwatch sw = new Stopwatch();
//sw.Start();
//var employeeEntityList = MapList1(o);
//sw.Stop();
//Console.WriteLine("ElapsedTicks Solution 1 (OfType): " + sw.ElapsedTicks);
//Console.WriteLine("--");
//sw = new Stopwatch();
sw.Start();
var employeeEntityList2 = MapList2(o);
sw.Stop();
Console.WriteLine("ElapsedTicks Solution 2 (let): " + sw.ElapsedTicks);
Console.ReadKey();
}
private static IEnumerable<object> AddMilionOfEmployees()
{
for (int i = 0; i < 100000; i++) //ideone doesn't allow a million.. ¬¬
{
Random randNum = new Random();
yield return new EmployeeDto { Id = i, Name = String.Format("Employee{0}", i * randNum.Next()) };
}
}
private static IEnumerable<EmployeeEntity> MapList1(List<object> o)
{
return
from i in o.OfType<EmployeeDto>()
select new EmployeeEntity
{
Id = i.Id,
FullName = i.Name
};
}
private static IEnumerable<EmployeeEntity> MapList2(List<object> o)
{
return
from si in o
let i = si as EmployeeDto
where i != null
select new EmployeeEntity
{
Id = i.Id,
FullName = i.Name
};
}
}