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 });
 
复制代码

 

posted @   竹林听雨行  阅读(221)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-08-28 MySQL - 修改数据库文件物理路径
点击右上角即可分享
微信分享提示