LINQ - 嵌套计数问题
问题描述:
我对客户及其订单有以下代码。我想列出所有的客户ID和相应的订单数量。我如何使用LINQ实现它?LINQ - 嵌套计数问题
注意:我是LINQ和var的新手。
protected void Page_Load(object sender, EventArgs e)
{
List<Order> orderListForCus1 = new List<Order>();
Order ord1 = new Order(1, new DateTime(2011, 9, 1));
Order ord2 = new Order(1, new DateTime(2011, 8, 1));
orderListForCus1.Add(ord1);
orderListForCus1.Add(ord2);
Customer cus1 = new Customer();
cus1.CustomerID = 1;
cus1.OrderList = orderListForCus1;
List<Customer> customerRecordsBook = new List<Customer>();
customerRecordsBook.Add(cus1);
var orderCounts = from c in customerRecordsBook
select new { c.CustomerID, OrderCount = c.OrderList.Count() };
}
答
你快到了。
你也可以遍历您的匿名类型的对象,就像任何其他对象:
foreach (var o in orderCounts) {
Response.Write(o.CustomerID + ": " + o.OrderCount + " orders");
}
注意o
必须声明为var
,因为类型还没有名字,你可以使用。
就你而言,你并不需要LINQ;你可以直接使用List<T>
:
foreach (var c in customerRecordsBook) {
Response.Write(c.CustomerID + ": " + c.OrderList.Count + " orders");
}
答
更新基于您的评论我的回答:
你不需要做from .. select
在所有。只是想迭代customerRecordsBook
,写你想要什么:
foreach (var c in customerRecordsBook)
{
Response.Write(string.Format("ID: {0}, Orders: {1}<br />",
c.CustomerID, c.OrderList.Count);
}
或者,更好的是,使用控制,如中继器或GridView控件,并设置customerRecordsBook作为数据源。
你已经有了。你在问什么? – SLaks
使用普通的'foreach'。 – SLaks