using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LinQStudy
{
class Program
{
static void Main(string[] args)
{
#region LinQ查询开头为J的名字并按升序方式输出结果
var names = new List<string> { "LiLei", "HanMeiMei", "Jeffer", "Jack", "Philip", "Rose" };
var nameWithJ = from n in names
where n.StartsWith("J")
orderby n
select n;
IEnumerator<string> GetName = nameWithJ.GetEnumerator();
while (GetName.MoveNext())
{
Console.WriteLine(GetName.Current);
}
#endregion
#region ToDictionary|ToLookup|GroupBy|LinQ的用法:将数据进行分组
List<Student> stuList = new List<Student>() { new Student(){RoomId=2001, Name="lily", Sex="男", Money=new int[]{10,5,20,30}},
new Student(){RoomId=2001, Name="asse", Sex="男", Money=new int[]{1,5,15,40}},
new Student(){RoomId=3001, Name="dg", Sex="女", Money=new int[]{60,5,2,30}},
new Student(){RoomId=1001, Name="ewt", Sex="女", Money=new int[]{35,5,20,30}} ,
new Student(){RoomId=3001, Name="王俊和", Sex="男", Money=new int[]{10,5,25,35}}
};
List<KTV> ktvList = new List<KTV>(){new KTV(){ BosName="LiFeng", CtreatYear=1998, RoomId=2001, RoomObjects=30},
new KTV(){ BosName="HanMeiMei", CtreatYear=2009, RoomId=1001, RoomObjects=70},
new KTV(){ BosName="ChenFei", CtreatYear=2014, RoomId=3001, RoomObjects=100},
};
//Dictionary<int,Student> dic=stuList.ToDictionary(i=>i.id);
//ToDictionary用法中如果Id相同,就会出错,这个时候微软提供了ToLookup;ToLookup分组查询
//IEnumerator<IGrouping<int, Student>> GetStuGroup = stuList.ToLookup(i => i.RoomId).GetEnumerator();
//GroupBy分组查询
//IEnumerator<IGrouping<int, Student>> GetStuGroup = stuList.GroupBy(j => j.RoomId).GetEnumerator();
//LinQ查询,按房间号降序排序分组
var people = from n in stuList
orderby n.RoomId descending
group n by n.RoomId into g
select g;
IEnumerator<IGrouping<int, Student>> GetStuGroup = people.GetEnumerator();
while (GetStuGroup.MoveNext())
{
Console.WriteLine("房间号:{0}", GetStuGroup.Current.Key);
IGrouping<int, Student> groupStu = GetStuGroup.Current;
IEnumerator<Student> GetStu = groupStu.GetEnumerator();
while (GetStu.MoveNext())
{
Student stu = GetStu.Current;
Console.WriteLine("姓名:{0} 性别:{1}", stu.Name, stu.Sex);
}
Console.WriteLine("");
}
//*******************************************************************************************************
//搜寻数组n中房间号为3001且性别男性的名字
var people1 = from n in stuList
where n.RoomId == 3001 && n.Sex == "男"
select n.Name;
List<string> stuName=people1.ToList();
//等同于==
List<string> stuName1=stuList.Where(r => r.RoomId == 3001 && r.Sex == "男").Select(r=>r.Name).ToList();
//获取类型为string的所有数据
object[] data = { "one",2,3,"four","five",6};
List<string> strList=data.OfType<string>().ToList();
//*******************************************************************************************************
//根据房间号从小到大,名字先后循序排列名字
var peple = from n in stuList
orderby n.RoomId, n.Name
select n.Name;
List<string> p=peple.ToList();
//等同于==
//OrderBy和ThenBy的用法
List<string> p1 = stuList.OrderBy(r => r.RoomId).ThenBy(n => n.Name).Select(n => n.Name).ToList();
//*******************************************************************************************************
//搜寻数组n中房间号为3001且性别男性的名字和房间号
var people2 = from n in stuList
where n.RoomId == 3001 && n.Sex == "男"
select new { Name = n.Name,Id = n.RoomId };
//等同于==
var p3 = stuList.OrderBy(r => r.RoomId).ThenBy(n => n.Name).Select(n => new { Name = n.Name, Id = n.RoomId });
foreach (var item in people2)
{
int id=item.Id;
string name = item.Name;
}
//******************************************************************************************************
//join..on...equals的用法 连接操作
var stuData = from s in stuList
select new { Name = s.Name, RoomId = s.RoomId, Sex = s.Sex };
var ktvData = from k in ktvList
select new { RoomId = k.RoomId, Year = k.CtreatYear, BosName = k.BosName, objectNum = k.RoomObjects };
var joinData = from s in stuData
join k in ktvData on s.RoomId equals k.RoomId
select new { Year = k.Year, Name = k.BosName, RoomId = s.RoomId, pName = s.Name, Sex = s.Sex };
foreach (var item in joinData)
{
int y = item.Year;
int r = item.RoomId;
string name=item.Name;
string sex = item.Sex;
string pName = item.pName;
}
//******************************************************************************************************
//复合的from子句,找出Student里面money有30的那个数据表,from子句用在子句也是一个数组集合的时候
var studentFrom = from s in stuList
from m in s.Money
where m == 30
orderby s.RoomId
select s.Name + " " + s.Sex;
IEnumerator<string> GetNameOrSex=studentFrom.GetEnumerator();
while (GetNameOrSex.MoveNext())
{
string dataFrom = GetNameOrSex.Current;
Console.WriteLine(dataFrom);
}
//等同于==
var ss = stuList.SelectMany(s => s.Money, (s, m) => new { Stu = s, Mony = m }).Where(d => d.Mony == 30).OrderBy(d => d.Stu.RoomId).Select(d => d.Stu.Name + " " + d.Stu.Sex);
foreach (var item in ss)
{
string ds = item;
Console.WriteLine(ds);
}
//******************************************************************************************************
//将要查询的语句定义成委托,后面用的时候直接调用Func(30)赋值;
Func<int, IEnumerable<string>> funcStu = monmey => from s in stuList
from m in s.Money
where m == monmey
orderby s.RoomId
select s.Name+" "+s.Sex;
//Intersect表示前一个集合中包含的值与后一个集合中包含的值进行交集,相关的操作有(Distinct非重复元素;Union并集;Except差集)
foreach (var item in funcStu(30).Intersect(funcStu(10)))
{
Console.WriteLine(item);
}
//******************************************************************************************************
//Zip的作用就是将2个不同的集合合并到一起,输入结果
var stuNamesOrSex = from s in stuList
where s.RoomId == 2001
select new { Name = s.Name, Sex = s.Sex };
var ktvs = from k in ktvList
where k.RoomId == 3001
select new { Name = k.BosName, Year = k.CtreatYear };
var zip=stuNamesOrSex.Zip(ktvs, (first, second) => "stu:" + first.Name + " " + first.Sex + "----" + "bos:" + second.Name + " " + second.Year);
foreach (var item in zip)
{
Console.WriteLine(item);
}
//******************************************************************************************************
//Range生成从1到100的数字,相关的操作(repeat,empty)
var values = Enumerable.Range(1,100);//从1到100,不重复
var Repeat = Enumerable.Repeat<int>(1, 20);//重复1,重复20次
var empty = Enumerable.Empty<int>();//返回一个空的集合
foreach (var item in values)
{
Console.WriteLine("{0}", item);
}
//******************************************************************************************************
//AsParallel并行查询,这个会自动启动任务管理器,运行CUP,在数据量比较大的时候,容易看得出来并行的优势。
var parallel = from x in stuList.AsParallel()
where x.RoomId > 1001
select x.Name;
foreach (var item in parallel)
{
Console.WriteLine(item);
}
//******************************************************************************************************
//Take()和Skip()等分区操作可用于分页,分页在windows和web应用程序中非常有用,可以只显示一部分数据给用户,
//比如我只想一页显示2个数据,如下:
int pageSize = 2;
int pageNumbers = stuList.Count % pageSize == 0 ? stuList.Count / pageSize : stuList.Count / pageSize + 1;
int pageNumbers2 = (int)Math.Ceiling(stuList.Count / (double)pageSize);
for (int page = 0; page < pageNumbers; page++)
{
var stus = (from s in stuList
select s.Name + " " + s.Sex).Skip(page * pageSize).Take(pageSize);
Console.WriteLine("第{0}页:", page + 1);
foreach (var item in stus)
{
Console.WriteLine(item);
}
}
//******************************************************************************************************
//let用来给查询计数
var query = from s in stuList
let number = s.Money.Count()
select new { Name = s.Name, Money = number };
foreach (var item in query)
{
Console.WriteLine("姓名:{0},Money个数:{1}", item.Name, item.Money);
}
//******************************************************************************************************
//WithCancellation用来对LinQ并行查询时通过令牌Token来取消查询
var cts = new CancellationTokenSource();
Task.Factory.StartNew(() => {
try
{
var res = from s in stuList.AsParallel().WithCancellation(cts.Token)
from m in s.Money
where m == 20 || m == 30 || m == 5
select s.Name + " " + s.Sex;
foreach (var item in res)
{
Console.WriteLine(item);
}
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
string input = Console.ReadLine();
if (input.Equals("y"))
cts.Cancel();
});
//******************************************************************************************************
//Cast<T>()为定义强类型化的查询,可以定义类型,通过类型来查询你想要的数据
var list = new System.Collections.ArrayList(stuList as System.Collections.ICollection);
var query1 = from r in list.Cast<Student>()
where r.Name == "lily"
select r;
foreach (var item in query1)
{
string sex = item.Sex;
}
//*******************************************************************************************************
#endregion
#region 通过OrderByDescending|LinQ方式将数组内的数据从大到小排列输出|LinQ的标准查询操作符
//******************************************************************************************************
//int[] strs = {11,10,3,2,4,7,8,1,5};
//int first = strs.First();//First获取数组首数据
//int last = strs.Last();//Last获取数组尾数据
//bool all = strs.All(i => i == 3);//All表示数组内的数据必须都是3才会为true,否则false,用来判断是否只存在某一个数据
//bool any=strs.Any(i => i == 3);//Any表示数组内的数据只要有一个为3就会为true,除非没有3才会为false,用来判断是否存在3这个数据
//int max=strs.Max();//Max获取数组中最大的数据
//int min = strs.Min();//Min获取数组中最小的数据
//List<int> take=strs.Take(3).ToList();//Take获取数组从0开始到指定数量的数据
//List<int> skip=strs.Skip(3).ToList();//Skip跳过数组从0开始到指定数量的数据,获取剩余数据
//int data=9;
//List<int> list = strs.ToList();
//int find = list.Find(i => i == data);//Find找出某一数据
//List<int> findAll = list.FindAll(i => i >= data);//FindAll找出所有满足条件的数据
//bool exists = list.Exists(i => i == data);//Exists找出是否存在某一个数据,存在为true,反则为false
//List<int> reverse = strs.Reverse().ToList();//Reverse反转数据存在List中
//List<int> where = strs.Where(i => i >= data).ToList();//where找出满足条件的是数据
//int[] toArray = list.ToArray();//ToArray就是讲集合转变成数组
//Dictionary<int, int> toDictionary = strs.ToDictionary(i => i);//ToDictionary将数组转变成字典集合,前提是数组中无重复的值,否则报错
//list.ForEach(i => Console.WriteLine(i));//ForEach将List集合中的数据循环输出
//list.Insert(1, 9);//Insert在指定的索引前添加指定的数值
//list.Remove(9);//Remove移除集合中指定的数值
//int single = list.Single(i => i == 3);//Single是否包含仅包含一个元素,如果包含多个,则就报错,否则返回数值
//list.Sort();//Sort将数据从小到大进行排序
//int sum=list.Sum(i=>i+1);//Sum将每一个元素加上指定的值后再求和
//IEnumerator<IGrouping<int, int>> lookup = strs.ToLookup(i => i).GetEnumerator();//ToLookup将数组转变成分组集合,解决了数组中重复值报错的问题
//while (lookup.MoveNext())
//{
// Console.WriteLine("key:{0}", lookup.Current.Key);
// IGrouping<int, int> groupInt = lookup.Current;
// IEnumerator<int> GetInt = groupInt.GetEnumerator();
// while (GetInt.MoveNext())
// {
// int intData = GetInt.Current;
// Console.WriteLine("value:{0}",intData);
// }
//}
//*******************************************************************************************************
通过OrderByDescending的方式来对数据进行由大到小的排列
方法一:
//IEnumerator<int> GetData = strs.OrderByDescending(i => i).GetEnumerator();
方法二:
var data = from n in strs
orderby n descending
select n;
List<int> list=data.ToList();//可以将数据转变成List集合
IEnumerator<int> GetData=data.GetEnumerator();
//while (GetData.MoveNext())
//{
// int str=GetData.Current;
// Console.WriteLine(str);
//}
#endregion
Console.ReadKey();
}
public class Student
{
public int RoomId;
public string Name;
public string Sex;
public int[] Money;
}
public class KTV
{
public int CtreatYear;
public string BosName;
public int RoomObjects;
public int RoomId;
}
}
}
Linq的学习
最新推荐文章于 2023-10-24 18:05:08 发布