LINQ~什么时候使用SelectMany和GroupBy
class PetOwner
{
public string Name { get; set; }
public List<Pet> 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<Pet>{new Pet{Id=1,Name="小狗"},new Pet{Id=2,Name="小猫"},new Pet{Id=3,Name="小老虎"} } },
new PetOwner { Name="zql",
Pet = new List<Pet>{new Pet{Id=1,Name="小狗"} } },
new PetOwner { Name="zhz",
Pet = new List<Pet>{new Pet{Id=1,Name="小狗"},new Pet{Id=3,Name="小老虎"} } },
};
List<Pet> PetList = new List<Pet>
{
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<Pet> query2 = new List<Pet>();
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<IGrouping<int, Pet>> query3 =
PetList.AsQueryable().GroupBy(pet => pet.Age, pet => pet);
foreach (IGrouping<int, Pet> petGroup in query3)
{
Console.WriteLine(petGroup.Key);
foreach (Pet pet in petGroup)
Console.WriteLine(" {0}", pet.Id+"..."+pet.Name);
}
#endregion
Console.ReadKey();
}
}