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 | 4 Comments

Selecting specific fields in linq query

The following simple linq query shows how to select specific fields in a linq object,

            var employees = from emp in new DataClassesDataContext().Employees
                            select new {
                                emp.LastName }; 

the same logic can be applied when ‘join’ is used in linq.

October 15, 2010 Posted by | Linq | 2 Comments

Linq to SQL with WCF

I worked in a task where I need to use linq to sql and WCF. In order to decorate linq to sql classes with WCF attributes, you need to set the “Serialization Mode’ to Unidirectional. This is a property of dbml file.

Once the property is set to Unidirectional, the classes created will have the WCF attributes (DataContract, DataMember) as shown below,

If you create custom classes, you need to add the WCF attributes manually, otherwise .NET will create for you automatically.

October 15, 2010 Posted by | ASP.NET, C#.NET, Linq | Leave a comment