Donatas
Donatas

Reputation: 1

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

Upvotes: 0

Views: 315

Answers (2)

Vishal Suthar
Vishal Suthar

Reputation: 17194

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460340

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.

Upvotes: 2

Related Questions