Loading

Linq-投影

1.把集合中的每一项转换为另外一种类型

IEnumerable<int> items = list.Select(it=>it.Age);
foreach (var item in items)
{
    Console.WriteLine(item);
}
IEnumerable<string> items = list.Where(it=>it.Salary>2500).Select(it=>it.Name+","+it.Age);
foreach (var item in items)
{
    Console.WriteLine(item);
}
IEnumerable<Dog> items = list.Select(it => new Dog { NickName = it.Name, Age = it.Age });
 foreach (Dog d in items)
{
    Console.WriteLine($"狗名:{d.NickName} 狗命:{d.Age}");
}



public class Dog
{
    public string NickName { get; set; }
    public int Age { get; set; }
}

2.匿名类型

//原理
var obj = new { AAA = "123", BBB = "qwe" };
Console.WriteLine(obj.AAA);
Console.WriteLine(obj.BBB);
//实战
var items = list.Select(e => new { XingMing = e.Name, NianLing = e.Age, XingBie = e.Gender ? "男" : "女" });

foreach (var item in items)
{
    Console.WriteLine($"XingMing = {item.XingMing}, NianLing = {item.NianLing}, XingBie = {item.XingBie}");
}

综合之前所学的内容,写一个复杂的需求:
Group + 投影 + 匿名
根据年龄分组,取工资最大值,工资最小值,总人数

var items = list.GroupBy(it => it.Age).Select(g => new { NianLing = g.Key, MaxS = g.Max(it => it.Salary), MinS = g.Min(it => it.Salary),RenShu = g.Count() });
foreach (var item in items)
{
    Console.WriteLine($"NianLing ={item.NianLing}, MaxS = {item.MaxS}, 
MinS = {item.MinS},RenShu = {item.RenShu}");
}
posted @ 2022-08-24 16:44  DotNeter-Hpf  阅读(26)  评论(0编辑  收藏  举报