Skip to content

Instantly share code, notes, and snippets.

@savaged
Created October 24, 2022 10:30
Show Gist options
  • Select an option

  • Save savaged/b9fabc242212101fdaa8284be7d0c48b to your computer and use it in GitHub Desktop.

Select an option

Save savaged/b9fabc242212101fdaa8284be7d0c48b to your computer and use it in GitHub Desktop.
C# SelectMany example
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; }
}
@savaged

savaged commented Oct 24, 2022

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment