扩展方法SelectMany无重载单一方式实现示例

本文介绍了一个自定义的 SelectMany 扩展方法实现,用于将多个集合扁平化为一个单一的序列。通过示例展示了如何从一组 PetOwner 对象中获取所有宠物的名字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. public static class myEnumerable
  5. {    
  6.     public static IEnumerable<S> SelectMany<T, S>(
  7.          this IEnumerable<T> source, Func<T, IEnumerable<S>> selector)
  8.     {
  9.         foreach (T item in source)
  10.         {            
  11.             IEnumerable<S>  Scollect=selector(item);
  12.             foreach (S child in Scollect)
  13.             {
  14.                 yield return child;
  15.             }           
  16.         }
  17.     }
  18. }
  19. class PetOwner
  20. {
  21.     public string Name { getset; }
  22.     public List<String> Pets { getset; }
  23. }
  24. class ExtensionMethods
  25. {
  26.     public static void Main()
  27.     {      
  28.          PetOwner[] petOwners = 
  29.          { 
  30.              new PetOwner { Name="Higa, Sidney",       Pets = new List<string>{ "Scruffy""Sam" } },
  31.              new PetOwner { Name="Ashkenazi, Ronen",   Pets = new List<string>{ "Walker""Sugar" } },
  32.              new PetOwner { Name="Price, Vernette",    Pets = new List<string>{ "Scratches""Diesel" } }
  33.          };
  34.          IEnumerable<string> query = petOwners.SelectMany(petOwner => petOwner.Pets);
  35.          Console.WriteLine("Using SelectMany():");
  36.          foreach (string pet in query)
  37.          {
  38.              Console.WriteLine(pet);
  39.          }
  40.         Console.ReadKey();
  41.     }
  42. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值