我需要将一个父列表和两个子列表合并为一个列表。我如何使用 C# 和 linq 来做到这一点?
这是我的代码...
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?
Run Code Online (Sandbox Code Playgroud)
因此,结果列表将包含看起来扁平化的项目,如下所示:
Joe, Blow, Visa, Master Card, 38 Oak Street, 432 Main Avenue
Sally、Cupcake、Discover、万事达卡、29 Maple Grove、887 Nut Street
它将展平客户的名字、姓氏、信用卡列表和地址列表。
感谢您的任何反馈!
实施IEnumerable:
public class Customer : IEnumerable<string>
{
public string FirstName {get; set;}
public string LastName {get; set;}
public List<CreditCard> CreditCards {get; set;}
public List<Address> Addresses{get; set;}
public IEnumerator<string> GetEnumerator()
{
yield return FirstName;
yield return LastName;
foreach (CreditCard c in CreditCards)
{
yield return c.ToString();
}
foreach (Address a in Addresses)
{
yield return a.ToString();
}
}
}
...
var result = allCustomers.SelectMany(c => c);
Run Code Online (Sandbox Code Playgroud)
注意:这只是一个例子。