使用Linq or Lambda进行查询,能感觉思路很清晰,昨天花了一个下午,今天花了一个下午,自己动手做了一些练习,总算是摸清了一些常用的操作。下面是我一些练习的代码。
int[] intarr = { 6, 1, 2, 3, 4, 5, 7, 8 };
string[] strarr = { "7", "10", "11", "8", "9" };
List list = new List
{
new Person(18,"well","a",800),
new Person(19,"mike","b",600),
new Person(25,"bruce","a",700),
new Person(28,"summer","b",500),
new Person(33,"energy","a",900),
new Person(50,"water","c",1000),
new Person(60,"spring","d",1200),
new Person(61,"fisher","a",1100),
new Person(65,"fish","a",400)
};
Console.WriteLine("====int类型排序====");
var tx1 = intarr.OrderBy(x => x);
foreach (var item in tx1)
{
Console.WriteLine(item);
}
Console.WriteLine("====string类型排序====");
var tx2 = strarr.OrderBy(x => Convert.ToInt32(x));
foreach (var item in tx2)
{
Console.WriteLine(item);
}
Console.WriteLine("====按年龄的降序排列====");
var tx3 = list.OrderByDescending(x => x.Age);
foreach (var item in tx3)
{
Console.WriteLine("年龄:{0} 名字:{1}", item.Age.ToString(), item.Name);
}
Console.WriteLine("======类型转换 string转int=====");
var tx4 = strarr.ToList().ConvertAll(x => Convert.ToInt32(x));
foreach (var item in tx4)
{
Console.WriteLine(item.GetType().ToString());
}
Console.WriteLine("=====类型转换 int转string======");
var tx5 = intarr.ToList().ConvertAll(x => x.ToString());
foreach (var item in tx5)
{
Console.WriteLine(item.GetType().ToString());
}
Console.WriteLine("====数据集合并(1)去除重复项====");
var tx6 = intarr.Union(strarr.ToList().ConvertAll(x => Convert.ToInt32(x))).OrderBy(x => x); ;
foreach (var item in tx6)
{
Console.WriteLine(item);
}
Console.WriteLine("====数据集合并(2)取并集====");
var tx7 = intarr.Concat(strarr.ToList().ConvertAll(x => Convert.ToInt32(x))).OrderBy(x => x);
foreach (var item in tx7)
{
Console.WriteLine(item);
}
Console.WriteLine("====常用的聚合函数(1)求总数====");
var tx8 = intarr.Sum();
Console.WriteLine("总数为:"+tx8.ToString());
Console.WriteLine("====常用的聚合函数(2)求平均数====");
Console.WriteLine("平均数为:"+intarr.Average().ToString());
Console.WriteLine("====求最大数,最小数====");
Console.WriteLine("最大数:{0} 最小数:{1}",intarr.Max().ToString(),intarr.Min().ToString());
Console.WriteLine("====以国家进行分组 求人数========");
var tx9 = list.GroupBy(x => x.Country);
foreach (var item in tx9)
{
Console.WriteLine("国家名:{0},人数:{1}",item.Key,item.Count().ToString());
}
Console.WriteLine("====以国家分组 求平均工资=======");
var tx10 = list.GroupBy(x => x.Country);
foreach (var item in tx10)
{
Console.WriteLine("国家名:{0},平均工资:{1}",item.Key,item.Average(x=>x.Pay).ToString());
}
Console.Read();