Frekster Frekster - 9 months ago 62
C# Question

C# LINQ how to flatten parent list and two nested children lists into a new list

I need to flatten a parent list and two child lists into one list. How can I do this using c# and linq?

Here is my code...

public class Customer
public string FirstName { get; set;}
public string LastName { get; set;}
// need to flatten these lists
public List<CreditCard> CreditCards { get; set;}
public List<Address> Addresses{ get; set;}

// Customer has CreditCards list and Addresses list
List<Customer> allCustomers = _db.GetAllCustomers();

// how to flatten Customer, CreditCards list, and Addresses list into one flattened record/list?

var result = allCustomers.GroupBy().SelectMany(); // how to flatten nested lists?

So the result list would contain items that look flattened like this:

Joe, Blow, Visa, Master Card, 38 Oak Street, 432 Main Avenue

Sally, Cupcake, Discover, Master Card, 29 Maple Grove, 887 Nut Street

It would flatten the customer FirstName, LastName, CreditCards list, and Addresses list.

Thanks for any feedback!

Answer Source

Use SelectMany if you want to flatten everything into one list. In this case, you are wanting a record per customer still, so you don't need to flatten.

For an array like your example, something like this should work:

var result = customers
   .Select(customer => new[]
   .Concat(customer.CreditCards.Select(cc => cc.ToString()))
   .Concat(customer.Addresses.Select(address => address.ToString())));