问题描述
嗨!
我想把头缠在LINQ上,但是我发现自己在这里苦苦挣扎.我有几个非常简单的课程:
Hi!
I''m trying to wrap my head around LINQ, but I find myself struggling here. I have a couple of very simple classes:
class Order
{
public string AccountNumber;
public string AccountName;
public List<OrderLine> OrderLines = new List<OrderLine>();
public DateTime StartDate;
public DateTime EndDate;
}
class OrderLine
{
public string Description;
public string ProductCode;
public double Duration;
public int Quantity;
}
在运行时,我用Orders实例填充了一个名为customerOrders的新List对象,该对象又具有多个OrderLine实例.现在,我想做的是选择在整个customerOrder对象中使用的独特ProductCode.我已经尝试了一下,并尝试了要塞,这是到目前为止我要提出的内容:
At run-time, I populate a new List object called customerOrders with instances of Orders, which again have multiple instances of OrderLine. Now, what I would like to do is to select the distinct ProductCode used in the entire customerOrder object. I have tried back and fort abit, and this is what I''ve come up with so far:
var c = from d in CustomerOrders select d.OrderLines.ToList();
IEnumerable<string> b = from q in (c as List<OrderLine>) select q.ProductCode;
第一行很好,但是下一行会导致异常,因为c为null.
我什至没有尝试从列表中查找不同的值:)
帮助和提示大加赞赏!
/Geir Rune
The first line is fine, but the next one causes an exception becase c is null.
I didn''t even get to trying to find the distinct values from the list :)
Help and tips much appreciated!
/Geir Rune
推荐答案
var orders = new List<Order>();
var distinctOrderLines = orders.SelectMany(order => order.OrderLines).Distinct();
这篇关于使用LINQ从列表中的列表中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!