简体   繁体   中英

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:

 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:

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. Since LINQ should not cause side effects i haven't modifed the Item.FailMessage property in the query but in the foreach -loop. Due to LINQ's deferred execution(the query gets executed at the foreach ) this is not less efficient.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM