博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LINQ~什么时候使用SelectMany和GroupBy
阅读量:7105 次
发布时间:2019-06-28

本文共 2059 字,大约阅读时间需要 6 分钟。

class PetOwner
{
public string Name { get; set; }
public List
Pet { get; set; }
}
 
class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
PetOwner[] petOwners =
{ new PetOwner { Name="zzl",
Pet = new List
{
new Pet{Id=1,Name="小狗"},new Pet{Id=2,Name="小猫"},new Pet{Id=3,Name="小老虎"} } },
new PetOwner { Name="zql",
Pet = new List
{
new Pet{Id=1,Name="小狗"} } },
new PetOwner { Name="zhz",
Pet = new List
{
new Pet{Id=1,Name="小狗"},new Pet{Id=3,Name="小老虎"} } },
};
 
List
PetList = new List
{
new Pet { Id = 1, Name = "小狗",Age=1 },
new Pet { Id = 2, Name = "小猫",Age=2 },
new Pet { Id = 3, Name = "小老虎",Age=1},
new Pet { Id = 4, Name = "小蛇",Age=3 },
new Pet { Id = 5, Name = "小蝎子",Age=2 },
new Pet { Id = 6, Name = "小兔子",Age=3},
};
 
#region 不知道SelectMany之前,选择LIST是多么的悲哀
List
query2 = new List
();
petOwners.AsQueryable().Where(i => i.Name == "zzl").ToList().ForEach(i =>
{
query2.AddRange(i.Pet);
});
foreach (Pet pet in query2)
Console.WriteLine(pet.Name);
#endregion
 
#region 有了SelectMany,我们的代码的可读及执行效率上都有所提高
 

List<Pet> query1 = petOwners.AsQueryable().Where(i => i.Name == "zzl")

.SelectMany(i => i.Pet).ToList();

query1.ForEach(i => Console.WriteLine(i.Name));
#endregion
 
#region GroupBy 在集合中根据某个字段进行分组
var query = PetList.AsQueryable().GroupBy(pet => pet.Age);
foreach (var ageGroup in query)
{
 

Console.WriteLine("Pet s' Age group: {0} Number of pets: {1}",

ageGroup.Key, ageGroup.Count());

}
#endregion
 
#region 对age属性进行分组,并把name显示出来
IEnumerable
> query3 =
PetList.AsQueryable().GroupBy(pet => pet.Age, pet => pet);
 
foreach (IGrouping
petGroup in query3)
{
Console.WriteLine(petGroup.Key);
foreach (Pet pet in petGroup)
Console.WriteLine("  {0}", pet.Id+"..."+pet.Name);
}
#endregion
 
 
Console.ReadKey();
}
}

转载于:https://www.cnblogs.com/lori/archive/2011/08/10/2133743.html

你可能感兴趣的文章
Oracle Goldengate REPLICAT启动时报正在运行解决办法
查看>>
Gdevops峰会归来
查看>>
[20170215]ORA-00088与DG Gap监测与解决4
查看>>
Hadoop Pig学习笔记(一) 各种SQL在PIG中实现
查看>>
充分挖掘大数据资源“富矿”
查看>>
oerr的用法
查看>>
解决GPG签名验证错误
查看>>
不属于自己的就忘掉吧,不要留恋,就当着是回忆吧…!
查看>>
文化衫、毕业纪念衫选用什么方式印刷合适?
查看>>
Spark亚太研究院决胜大数据时代100期公益大讲堂
查看>>
删除多target工程
查看>>
NSRunLoop详解
查看>>
[From Microsoft] Using command redirection oper...
查看>>
C++11新特性:std::move()和std::forward()
查看>>
springMVC+jpa配置之简单案例
查看>>
centos6.0 安装jdk
查看>>
R 学习笔记《七》 R语言初学者指南--简单函数
查看>>
从“疑似12306密码泄露”新闻中思考暗网事件跟进与追踪的方法
查看>>
Zabbix监控tcpstatus
查看>>
【转】当今在世智商最高的十大天才
查看>>