I was working on this scenario
and breaking my head to come up with simple solution to compare two large list
of object (List<object>) and get the result as new (Insert), update and
delete data. Found out that there is simple solution and I thought will publish
it so that it can help others.
I have put generic code which
anyone can copy and start using right away.
New data
|
/// <summary>
/// Returns the newly added
/// </summary>
/// <param name="existingData">Existing data</param>
/// <param name="newData">New data</param>
/// <returns>List
of objects which are newly added</returns>
public List<object>
GetInsertData(List<object> existingData, List<object> newData)
{
// Local
objects
List<object> returnList = null;
// Prepare the list which has the data to be inserted
returnList = (from New in newData
join Existing in existingData on New.ID equals Existing.ID
into DataAdded
from dataOld in DataAdded.DefaultIfEmpty()
where dataOld == null
select New).ToList<object>();
// Return the
data list
return returnList;
}
|
Updated data
|
/// <summary>
/// Returns the data updated
/// </summary>
/// <param name="existingData">Existing data</param>
/// <param name="newData">New data</param>
/// <returns>List
of objects which are updated</returns>
public List<object> GetUpdateData(List<object> existingData,
List<object> newData)
{
// Local
objects
List<object> returnList = null;
returnList = (from New in newData
join Existing in existingData on New.ID equals Existing.ID
into DataUpdated
from dataOld in
DataUpdated.DefaultIfEmpty()
where dataOld!= null &&
(New.<Field1>!= dataOld.<Field1> || New.<Field2> !=
dataOld.<Field2>)
select new object
{
Field1 = New.Value1,
Field2 = New.Value2,
Field3 = dataOld.Value3,
Field4 = dataOld.Value4,
}).ToList<object>();
// Return the data list
return returnList;
}
|
Delete data
|
/// <summary>
/// Returns the deleted rows
/// </summary>
/// <param name="existingData">Existing data</param>
/// <param name="newData">New data</param>
/// <returns>List
of schools which needs to be deleted</returns>
public List<object> GetDeleteData(List<object> existingData,
List<object> newData)
{
// Local
objects
List<object> returnList = null;
// Prepare the list which has the data to be deleted
returnList = (from Existing in existingData
join New in newData on Existing.ID equals New.ID
into NewWithNullForDeleted
from
subNew in
NewWithNullForDeleted.DefaultIfEmpty()
where
subNew == null
select
Existing).ToList<School>();
// Return the
data list
return returnList;
}
|
Please leave your feedback and queries in the comments
section. Thank you!
No comments:
Post a Comment