[英]comparing two lists in linq
I have two lists: orders and items and I need to compare them by their name AND then look if order list have bool set to false and if it satysfy the condition it copies its string message and then adds to new list and I just have no freaking idea even how to compare lists, so any help will be appreciated Function: 我有两个列表:订单和项目,我需要按名称进行比较,然后查看订单列表是否将bool设置为false,以及是否满足条件,它会复制其字符串消息,然后添加到新列表中,但我没有吓人的想法,甚至如何比较列表,所以任何帮助将不胜感激功能:
private static void FailedItemsList(List<Item> failed, List<Order> orders, List<Item> items)
{
foreach(var order in orders)
{
foreach(var item in items)
{
if(order.Equals(item))
{
if(order.Fulfilled == false)
{
item.FailMessage = order.FailMessage;
failed.Add(item);
}
}
}
}
}
In general i would return this "fail-list" from the method instead of passing it to it. 通常,我将从方法中返回此“失败列表”,而不是将其传递给它。 You could use LINQ to simplify this task:
您可以使用LINQ简化此任务:
static List<Item> GetFailedItems(List<Order> orders, List<Item> items)
{
var failed = from order in orders
where !order.Fulfilled
join item in items on order.Name equals item.Name
select new { order, item};
List<Item> failedItems = new List<Item>();
foreach (var x in failed)
{
x.item.FailMessage = x.order.FailMessage;
failedItems.Add(x.item);
}
return failedItems;
}
Since Item
and Order
are different classes i have removed the Equals
check and replaced it with a join on the Name
property as desired. 由于
Item
和Order
是不同的类,因此我删除了Equals
检查,并根据需要将其替换为Name
属性上的联接。 Since LINQ should not cause side effects i haven't modifed the Item.FailMessage
property in the query but in the foreach
-loop. 由于LINQ不会引起副作用,因此我没有在查询中而是在
foreach
-loop中修改了Item.FailMessage
属性。 Due to LINQ's deferred execution(the query gets executed at the foreach
) this is not less efficient. 由于LINQ的执行延迟(查询在
foreach
处执行),所以效率也不低。
var v = from x in orders
where x.Fulfilled == false
join item in items on order.Name equals item.Name
select x.FailMessage;
foreach (int i in v)
failed.Add(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.