JG Vimalan's Blog

It is all about coding!

Compare two generic lists using Linq

I got a task where I need to compare 2 generic lists and find the modified records. Here is the source code,

We are going to compare ‘List<SalesOrder> oldSalesOrderList’ and ‘List<SalesOrder> sqlSalesOrderList’ and find out the modified records.

        public static List<Entities.SalesOrder> GetModifiedRecords(this List<SalesOrder> oldSalesOrderList, List<SalesOrder> sqlSalesOrderList)
            var result = (from oraSalesOrder in oldSalesOrderList
                         from sqlSalesOrder in sqlSalesOrderList
                         ((oraSalesOrder.BillToAddress != sqlSalesOrder.BillToAddress ||
                         oraSalesOrder.BillToAddressId != sqlSalesOrder.BillToAddressId ||
                         oraSalesOrder.BillToCity != sqlSalesOrder.BillToCity ||
                         oraSalesOrder.BillToSite != sqlSalesOrder.BillToSite                         
                         && (oraSalesOrder.Id == sqlSalesOrder.Id &&
                         oraSalesOrder.LineNo == sqlSalesOrder.LineNo
                         select oraSalesOrder).Distinct();

            List<SalesOrder> modifiedSalesOrder = new List<SalesOrder>(result);
            return modifiedSalesOrder;           

Thats it! Now, you will get the modified records in a separate generic list.


April 16, 2011 - Posted by | C#.NET, Linq


  1. Have a look at this.

    List commonItems = type1List.Where(t1 => type2List.Select(t2 => t2.ID).Contains(t1.ID)).ToList();
    Console.WriteLine(“The two lists contain {0} members in common”, commonItems.Count);

    Comment by Parthasarathy | May 3, 2011 | Reply

    • Hello Vimalan and Parthasarathy

      I have plenty of records in generic list where combination of two fields form the unique identifier. And, I need to compare two generic lists of same type say, ‘List src’ with ‘List dest’ and find out the common records and new records. In the abc class, I have around 20 fields. Can you post some code samples to achieve this?


      Comment by Kannan | May 18, 2011 | Reply

  2. Nice, its work for me, thanks a lot….

    Comment by Sheik Mohamed | October 29, 2012 | Reply

  3. Nice Post

    Comment by Sudharsan | April 8, 2013 | Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: