jQuery and ASP.NET

July 26, 2010

List Common Elements between two List<string>




Here’s a simple post that shows how to list common elements between two List<Strings>. Use the Enumerable.Intersect method

C#

class Program
{
static void Main(string[] args)
{
List<string> lstOne =
new List<string>() { "Jim", "Jack", "Kate", "Nope" };
List<string> lstTwo =
new List<string>() { "Jack", "Nope", "Jim" };
IEnumerable<string> lstNew = null;

// Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);

Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)
Console.WriteLine(s);
Console.WriteLine("-------------");
}
}

VB.NET


    Sub Main()
Dim lstOne As New List(Of String)() _
From {"Jim", "Jack", "Kate", "Nope"}
Dim lstTwo As New List(Of String)() _
From {"Jack", "Nope", "Jim"}
Dim lstNew As IEnumerable(Of String) = Nothing

' Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)

Console.ReadLine()
End Sub

Private Sub
PrintList(ByVal str As IEnumerable(Of String))
For Each s In str
Console.WriteLine(s)
Next s
Console.WriteLine("-------------")
End Sub

OUTPUT


image


Read some more tips in my article over here Some Common Operations using List<string>



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "List Common Elements between two List<string>"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions