Tuesday, February 7, 2012

Compare to List using C# and LINQ

LINQ offers developers a lot of useful features by which developers can solve more complex solution in a easy way. Today our discussion about comparison of two lists or collections.

Sample code 1:

static void Main(string[] args)
{
List strList1 = new List{"Jack","And","Jill","Went","Up","The","Hill"};
List strList2 = new List{"Jack", "And", "Jill", "Went", "Down", "The", "Hill"};

Console.WriteLine("Except result ...........");
var lstExcept = strList2.Except(strList1);
foreach (var variable in lstExcept)
{
Console.WriteLine(variable);
}

Console.WriteLine("Insect result ...........");
var lstInsect = strList2.Intersect(strList1);
foreach (var variable in lstInsect)
{
Console.WriteLine(variable );
}

Console.WriteLine("Union result ...........");
var lstUnion = strList2.Union(strList1);
foreach (var variable in lstUnion)
{
Console.WriteLine(variable );
}
Console.ReadLine();
}

Output:



Note that if you want to, say, ignore case:

List except = listA.Except(listB, StringComparer.OrdinalIgnoreCase);
You can replace the last parameter with an IEqualityComparer of your choosing.

You can get more information from here.

Sample code 2:
In sample code 1 just showing simple implementation. Now showing some more complex implementation.

This solution produces a result list, that contains all differences from both input lists. You can compare your objects by any property, in my example it is ID. The only restriction is that the lists should be of the same type:

var DifferencesList = ListA.Where(x => !ListB.Any(x1 => x1.id == x.id))
.Union(ListB.Where(x => !ListA.Any(x1 => x1.id == x.id)));

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...