我是LINQ的新手,所以显然在编写查询方面遇到了困难。
这是我的代码:
public class Customer
{
public int cid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
public class Order
{
public int Orderid { get; set; }
public int customerid { get; set; }
public int Quantity { get; set; }
}
static void Main(string[] args)
{
List<Customer> customerList = new List<Customer>
{
new Customer(){cid=1,FirstName="Avinash",LastName="Kothamasu",City="Chennai"},
new Customer(){cid=2,FirstName="Abhiram",LastName="Kumar",City="Chennai"},
new Customer{cid=3,FirstName="Balu",LastName="Chinna",City="Chennai"},
new Customer{cid=4,FirstName="Sai",LastName="Kothamasu",City="Bhimavaram"},
new Customer{cid=5,FirstName="Harshita",LastName="Kothamasu",City="Bhimarvarm"},
new Customer{cid=6,FirstName="Mounika",LastName="Kothamasu",City="Guntur"}
};
List<Order> orderList = new List<Order>
{
new Order(){Orderid=11,customerid=1,Quantity=20},
new Order(){Orderid=111,customerid=1,Quantity=10},
new Order(){Orderid=22,customerid=2,Quantity=15},
new Order(){Orderid=222,customerid=2,Quantity=8},
new Order(){Orderid=22222,customerid=2,Quantity=50},
new Order(){Orderid=33,customerid=3,Quantity=10},
new Order(){Orderid=333,customerid=3,Quantity=5},
new Order(){Orderid=44,customerid=4,Quantity=4},
new Order(){Orderid=55,customerid=5,Quantity=1},
new Order(){Orderid=66,customerid=6,Quantity=2}
};
var OrderListforCustomers = from c in customerList
join o in orderList on
c.cid equals o.customerid
where o.Quantity > 1 && o.Quantity <= 50
group new { c, o } by new { o.customerid, c.FirstName, c.LastName, c.City } into customergroups
orderby customergroups.Key.customerid
select new
{
CustomerID = customergroups.Key.customerid,
CustomerName = customergroups.Key.FirstName.ToUpper() + " , " + customergroups.Key.LastName.ToUpper(),
City = customergroups.Key.City,
MaximumQuantityCount = customergroups.Select(x=>x.o).Max(x=>x.Quantity),
*OrderIDwithMaxQuanCount=customergroups.Select(x=>x.o.Orderid).Where();*
};
Console.Write("CID" + " || ");
Console.Write("CustomerName" + " || ");
Console.Write("City" + " | ");
Console.Write("MaximumQuantityCount" + " || ");
Console.Write("OrderIDwithMaxCount");
Console.WriteLine(Environment.NewLine);
foreach (var custgroup in OrderListforCustomers)
{
Console.Write(custgroup.CustomerID + " || ");
Console.Write(custgroup.CustomerName + " || ");
Console.Write(custgroup.City + " || ");
Console.Write(custgroup.MaximumQuantityCount + " || ");
Console.Write(Environment.NewLine);
Console.ReadLine();
在这里,我要做的是打印客户详细信息以及订单详细信息和一些条件。
我需要打印具有最大数量的客户的订单
我能够为特定客户提供MaxOrderCount,但无法获取具有最大数量的订单ID
在查询中,select子句中的最后一行,我在如何编写
方面遇到了一些困难请帮助..
答案 0 :(得分:4)
您可以先订购,然后选择如下:
OrderIDwithMaxQuanCount=customergroups.OrderByDescending(x => x.o.Quantity)
.Select(x => x.o.Orderid).FirstOrDefault()