static class Helper {
public static T Cast<T>(this object obj, T sample)
{
//类型推导功能
return (T)obj;
}
}
public static class Helper2
{
public static string ShowTime(this String obj)
{
return obj + DateTime.Now.ToString();
}
}
class Program
{
static void Main(string[] args)
{
#region 匿名类型的局部变量
//var str = "Hello";
//var num = 22.3;
//var arr = new[] { "1", "2", "3" };
//foreach (var item in arr)
//{
// Console.WriteLine(item);
//}
#endregion
#region 匿名类型
//var Test = new { name = "zhangsan", id = 12 };
//Console.WriteLine(Test.name);
#endregion
#region 扩展方法
//var abc = "hello".ShowTime();
//Console.WriteLine(abc);
#endregion
#region 对象初始化器
#endregion
#region 集合初始化器
List<String> list = new List<string>() { "1","3","ggf"};
foreach (var item in list)
{
Console.WriteLine(item);
}
#endregion
#region Lambda表达式
//所谓Lambda表达式实际上是对一个集合进行数据筛选和计算用的
List<object> user = new List<object>{
new {Id=1,Name="YJingLee",Age=22},
new {Id=2,Name="XieQing",Age=25},
};
//获取特定人时所用的过滤条件,p参数属于User类型
var results = user.Where(p => p.Cast(new { Id = 0, Name = string.Empty, Age = 0 }).Name == "XieQing").ToList();
foreach (var item in results)
{
Console.WriteLine(item.Cast(new { Id = 0, Name = "", Age = 0 }).Name);
}
//用User对象的Age值计算平均年龄
var average = user.Average(p => p.Cast(new { Id = 0, Name =string.Empty, Age = 0 }).Age);
#endregion
}
}