Created
October 24, 2022 10:30
-
-
Save savaged/b9fabc242212101fdaa8284be7d0c48b to your computer and use it in GitHub Desktop.
C# SelectMany example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Lease[] leases = | |
| { new Lease { Leasee = "David", | |
| Assets = new List<string>{ "Workstation18", "Laptop5" } }, | |
| new Lease { Leasee = "Pawel", | |
| Assets = new List<string>{ "Workstation30" } }, | |
| new Lease { Leasee = "Rhys", | |
| Assets = new List<string>{ "Workstation24", "Headset3" } }, | |
| new Lease { Leasee = "Karen", | |
| Assets = new List<string>{ "Laptop31", "MS-Keyboard", "Headset2" } } }; | |
| foreach (var i in Flatten(leases)) | |
| { | |
| Console.WriteLine("Leasee: {0}, Asset: {1}", i.Leasee, i.Asset); | |
| } | |
| static IEnumerable<LeaseRow> Flatten(Lease[] leases) | |
| { | |
| return leases | |
| .SelectMany(lease => lease.Assets, | |
| (lease, asset) => new { lease, asset }) | |
| .Select(leaseAndAsset => | |
| new LeaseRow { | |
| Leasee = leaseAndAsset.lease.Leasee, | |
| Asset = leaseAndAsset.asset | |
| } | |
| ); | |
| } | |
| record struct Lease | |
| { | |
| public string Leasee { get; set; } | |
| public IList<string> Assets { get; set; } | |
| } | |
| record struct LeaseRow | |
| { | |
| public string Leasee { get; set; } | |
| public string Asset { get; set; } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on the MSDN doco for SelectMany