简体   繁体   中英

Compare two generic lists using Linq

I'm trying to compare two generic list using following query, just want to insert modified values only

so I wrote following

public ActionResult GetModifiedRecords(IEnumerable<SalesOrder> oldSalesOrderList, List<SalesOrder> newSalesOrderList)
{
    var result = (from oldSalesOrder in oldSalesOrderList
                  from newSalesOrder in newSalesOrderList
                  where
                  (oldSalesOrder.Value != newSalesOrder.Value)
                  select oldSalesOrder).Distinct();
    IEnumerable<SalesOrder> modifiedSalesList = new List<SalesOrder>(result);
    return modifiedSalesOrder;           
}

but this seems not working

Note : The return type of your Linq Query will be IEnumerable you need to not create it again by casting;

Have you tried something like this:

public IEnumerable<SalesOrder> GetModifiedRecords(IEnumerable<SalesOrder> oldSalesOrderList, List<SalesOrder> newSalesOrderList)
{
    return oldSalesOrderList.Where((x,i)=>newSalesOrderList[i].Value !=x.Value);  
}

Above code will works only if both Lists are of same order, if not you can try something like this(Assume that OrderId will be an unique field):

return oldSalesOrderList.Where(x =>
       newSalesOrderList.Any(y => y.OrderId == x.OrderId && Y.Value !=x.Value));  

You can get the modified records like so:

    var modifiedRecords = newSalesOrderList.Where(a => oldSalesOrderList.All(b => b.Value != a.Value));

I dont really understand what you are doing. but based on your question. that should work.

You have the solution on how to do it, from the other answers, but let me explain why your original query was not working. Imagine you call your method with these 2 lists:

var list1 = new List<SalesOrder> 
    { new SalesOrder { Value = 1 }, new SalesOrder { Value = 2 } };
var list2 = new List < SalesOrder > 
    { new SalesOrder { Value = 1 }, new SalesOrder { Value = 3 } };
var res = GetModifiedRecords(list1, list2);

Your query will take the first item from list1 and compare it against the first item of list2 and it will notice they are the same so it will not select it. Then it will compare the first item from list1 against the 2nd item in list2 and since they are not equal it will select the first item from list1 even though you were not expecting this. Then it will do the same for the 2nd item from list1 . So the end result, it will return both items from list1 even though you were expecting only the difference.

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