如何使用IEnumerable创建LINQ查询



我有一个任务要实现一个返回IEnumerable<gt;。

/// <summary>
/// Calculates for each customer count of his orders.
/// </summary>
/// <returns>The sequence of customers and how many orders each has.</returns>
public static IEnumerable<(string customerId, int orderCount)> CustomersOrdersCount()
{
List<Customer> customers = Customers.CustomerList;
IEnumerable<(string customerId, int orderCount)> query = from c in customers
from co in c.Orders
select (customerId: c.CustomerId, orderCount: (int)c.Orders.Length);
return query;
}

(这是我的实现,不起作用(

以下是客户类别:

namespace Linq.DataSources
{
public static class Customers
{
public static List<Customer> CustomerList { get; } =
(from e in XDocument.Parse(InputValues.CustomersXml).Root?.Elements("customer")
select new Customer
{
CustomerId = (string) e.Element("id"),
CompanyName = (string) e.Element("name"),
Address = (string) e.Element("address"),
City = (string) e.Element("city"),
Region = (string) e.Element("region"),
PostalCode = (string) e.Element("postalcode"),
Country = (string) e.Element("country"),
Phone = (string) e.Element("phone"),
Orders = (
from o in e.Elements("orders").Elements("order")
select new Order
{
OrderId = (int) o.Element("id"),
OrderDate = (DateTime) o.Element("orderdate"),
Total = (decimal) o.Element("total")
}).ToArray()
}).ToList();
}
}

订单类别:

namespace Linq.DataSources
{
public class Order
{
public int OrderId { get; set; }

public DateTime OrderDate { get; set; }

public decimal Total { get; set; }

public override string ToString() => $"{OrderId}: {OrderDate:d} for {Total:C2}";
}
}

基本上,任务是返回(Customer_Id,How_Many_Orders_Each_Customer_Has(

不确定我是否遗漏了任何细节,但应该直截了当。我们不需要来自合作伙伴的订单:-

from c in customers                                                             
select (customerId: c.CustomerId, orderCount: c.Orders.Length);

最新更新