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 @ 2022-08-28 21:20  竹林听雨行  阅读(176)  评论(0编辑  收藏  举报