相关:https://www.cnblogs.com/zhaopei/p/5746414.html
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqTest
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string Height { get; set; }
public string Weight { get; set; }
}
class Program
{
static List
{
var persons = new List
{
new Person{ Id=1,Name="henry1",Age=1,Sex="B",Height="11",Weight="111"},
new Person{ Id=2,Name="henry2",Age=2,Sex="B",Height="22",Weight="222"},
new Person{ Id=3,Name="henry3",Age=3,Sex="B",Height="33",Weight="333"},
new Person{ Id=4,Name="henry4",Age=4,Sex="B",Height="44",Weight="444"},
new Person{ Id=5,Name="henry5",Age=5,Sex="G",Height="55",Weight="555"},
new Person{ Id=6,Name="henry6",Age=6,Sex="G",Height="66",Weight="666"},
new Person{ Id=7,Name="henry7",Age=7,Sex="G",Height="77",Weight="777"},
new Person{ Id=8,Name="henry8",Age=8,Sex="G",Height="88",Weight="888"},
};
return persons;
}
static void Main(string[] args)
{
var persons = GetPersons();
//linq查询表达式
var test1 = from per in persons
where per.Age > 3
select per;
foreach (var item in test1)
{
//test1列表含有Person类的所有字段
Console.WriteLine("test1--"+item.Name + "--" + item.Age + "--" + item.Weight);
}
Console.WriteLine();
//点标记,lambda
var test3 = persons.Where(p => p.Age > 3).ToList();
foreach (var item in test3)
{
//test3列表含有Person类的所有字段
Console.WriteLine("test3--"+item.Name + "--" + item.Age + "--" + item.Weight);
}
Console.WriteLine();
//linq查询表达式
var test2 = from per in persons
where int.Parse(per.Weight) > 300
orderby per.Age
select new { per.Age, per.Name, per.Sex };
foreach (var item in test2)
{
//test2列表只有Age Name Sex三个字段
Console.WriteLine("test2--"+item.Name + "--" + item.Age + "--" + item.Sex);
}
Console.WriteLine();
//点标记(Lambda)
var test4 = persons.Where(e => int.Parse(e.Weight) > 300)
.OrderBy(e => e.Age)
.Select(p => new { p.Age, p.Name, p.Sex })//匿名类
.ToList();
foreach (var item in test4)
{
//test4列表只有Age Name Sex三个字段
Console.WriteLine("test4--"+item.Name + "--" + item.Age + "--" + item.Sex);
}
Console.WriteLine();
//很多情况下linq和lambda可以相互装转换,以上就是
//下面这种情况只能使用lambda
var test5 = persons
.Where((p,index) => p.Age > 3 && index%2==0)
.Select((p,index)=>new { p,index})
.Reverse()//反序
.ToList();
//test5.Distinct().ToList();//去重
//test5.Except(testn).ToList();//差集
//test5.Union(testn).ToList();//并集
//test5.Intersect(testn).ToList();//交集
foreach (var item in test5)
{
Console.WriteLine("test5--"+item.index + "--" + item.p.Id + "--" + item.p.Name + "--" + item.p.Weight);
}
Console.WriteLine();
Console.ReadLine();
}
}
}