我是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);
我真的在努力了解正在发生的事情,因此,如果您可以帮助我,请向我解释一下您如何得出这样的结论:)
非常感谢您的光临!
答案 0 :(得分:0)
您当前的查询:
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
读为“对于cus
数组中代表customers
的每个客户,其中客户所在的城市为“ 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”的产品保留了该特定客户。
答案 1 :(得分:0)
LINQ查询是管道:数据从一个子句到另一个子句在流中逐元素流动。从某些数据源中,您可以获取元素流(例如,通过AsEnumerable
)。您可以从元素流中对某些谓词进行过滤(对返回布尔值的元素执行功能),仅将谓词接受的那些元素(返回为true)保留在该流中,并丢弃其他元素。该过滤器称为WHERE,谓词是WHERE子句的其余部分,例如WHERE cus.City == "G"
。而且,还可以从流中的元素中选择一个字段,将流从(原始)元素的流更改为字段的流。这是一个SELECT,例如SELECT g.City
,其中的流程将从客户流变为字符串流(每个字符串都是城市名称)。
由此(以及您可以学习的其他LINQ子句),您可以构建所需的任何数据管道。具体来说,如果客户订购了牛奶,它会返回一系列客户名称。