lambda selectMany (就是将查询出来的多个集合,合并到一起,返回一个合并后的集合)
https://www.cnblogs.com/micoos/articles/16350796.html
.NET(C#) Linq Select和SelectMany的使用及区别
https://www.cjavapy.com/article/2464/
class Person { public string Name { set; get; } public int Age { set; get; } public string Gender { set; get; } public Dog[] Dogs { set; get; } } public class Dog { public string Name { set; get; } } List<Person> personList = new List<Person> { new Person { Name = "P1", Age = 18, Gender = "Male", Gogs = new Dog[] { new Dog { Name = "D1" }, new Dog { Name = "D2" } } }, new Person { Name = "P2", Age = 19, Gender = "Male", Gogs = new Dog[] { new Dog { Name = "D3" } } }, new Person { Name = "P3", Age = 17,Gender = "Female", Dogs = new Dog[] { new Dog { Name = "D4" }, new Dog { Name = "D5" }, new Dog { Name = "D6" } } } };
我们可以看到p1对应D1,D2
p2对应D3 p3对应D4D5D6
最基本用法
var dogs = personList.SelectMany(p => p.Dogs); foreach (var dog in dogs) { Console.WriteLine(dog.Name); }
var dogs = personList.SelectMany((p, i) => p.Dogs.Select( d=> { d.Name = $"{i},{d.Name}"; return d; }));
var results = personList.SelectMany(p => p.Dogs, (p, d) => new { PersonName = p.Name, DogName = d.Name }); foreach (var result in results) { Console.WriteLine($"{result.PersonName},{result.DogName}"); } // p就是前面的p,也就是迭代对象 d是p.dogs 里面的元素,也就是dog 第二个参数类似于SQL的交叉集合
var results = personList.SelectMany((p,i) => { for(int j=0;j<p.Dogs.Length;j++) { p.Dogs[j].Name = $"{i}-{p.Dogs[j].Name}"; } return p.Dogs; }, (p, d) => new { PersonName = p.Name, DogName = d.Name });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2021-08-28 MySQL - 修改数据库文件物理路径