gpt4 book ai didi

c# - LINQ 子选择

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:09 25 4
gpt4 key购买 nike

我是一名学生,刚接触 LINQ,我们接到了一项处理 LINQ 查询的任务。

我的问题是过去几天我一直在努力寻找执行此步骤的正确方法:打印订单中包含“牛奶”的客户姓名。

Write a LINQ query to select all customers buying milk.
Print the Name of each customer in the query.

为了节省时间,这里是数据的结构,以便您理解它:

        Product milk    = new Product { Name = "Milk",    Price = 13.02m };
Product butter = new Product { Name = "Butter", Price = 8.23m };
Product bread = new Product { Name = "Bread", Price = 17.91m };
Product cacao = new Product { Name = "Cacao", Price = 25.07m };
Product juice = new Product { Name = "Juice", Price = 17.03m };

Customer c1 = new Customer { Name = "x", City = "g", Orders = new Order[] {
new Order { Quantity = 2, Product = milk },
new Order { Quantity = 1, Product = butter },
new Order { Quantity = 1, Product = bread }
}
};

Customer c2 = new Customer { Name = "y", City = "g", Orders = new Order[] {
new Order { Quantity = 1, Product = cacao },
new Order { Quantity = 1, Product = bread },
new Order { Quantity = 2, Product = milk },
new Order { Quantity = 2, Product = butter },
}
};

Customer c3 = new Customer { Name = "z", City = "g", Orders = new Order[] {
new Order { Quantity = 3, Product = juice }
}
};

Customer[] customers = new Customer[] { c1, c2, c3 };

作为我在 LINQ 中使用的语法示例,这里是工作代码的引用:

        var QueryCustomerByCity = from cus in customers.AsEnumerable()
where cus.City == "g"
select cus;

foreach (Customer c in QueryCustomerByCity)
Console.WriteLine("Customer {0} lives in {1}", c.Name, c.City);

我真的很努力去理解发生了什么,所以如果你能帮助我,请解释一下你是如何得出这样的结论的:)

非常感谢您的宝贵时间!

最佳答案

您当前的查询:

var QueryCustomerByCity = from cus in customers.AsEnumerable() //for each customer in customers 
where cus.City == "g" // where the Customer is from the City "g"
select cus; // select the customer

读作“对于每个在 customers 数组中表示为 cus 的客户,其中 customers City 为“g”,然后保留该客户”。因此,您将拥有一系列客户,他们的城市是“g”。

至于你的任务,你追求的是:

var result = from cus in customers // for each customer in customers                  
where cus.Orders.Any(o => o.Product.Name == "Milk") // where the product name is "Milk"
select cus; // select the customer

这实际上遍历了 customers 数组中的客户并检查他们的订单,如果有任何产品名称为“Milk”,则保留该特定客户。

关于c# - LINQ 子选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com