Some Common Operations using List - Part I

Posted by: Suprotim Agarwal , on 1/15/2010, in Category LINQ
Views: 123035
Abstract: In this article, I will demonstrate some common operations on List using LINQ
Some Common Operations using List<string> - Part I
 
I have been writing some articles in the past where I try and demonstrate the capabilities of LINQ using some common examples. Some of these articles are:
In this article and the next one, I will demonstrate some common operations on List<string> using LINQ. I assume that you are familiar with LINQ.
Here are the sample List<string> for demonstration purposes. The VB.NET code has been converted using a conversion tool and accuracy has not been tested.
C#
List<string> lstOne = new List<string>() { "January", "February", "March"};
List<string> lstTwo = new List<string>() { "January", "April", "March"};
List<string> lstThree = new List<string>() { "January", "April", "March", "May" };
List<string> lstFour = new List<string>() { "Jan", "Feb", "Jan", "April", "Feb" };
IEnumerable<string> lstNew = null;
VB.NET
Dim lstOne As New List(Of String) (New String() {"January", "February", "March"})
Dim lstTwo As New List(Of String) (New String() {"January", "April", "March"})
Dim lstThree As New List(Of String) (New String() {"January", "April", "March", "May"})
Dim lstFour As New List(Of String) (New String() {"Jan", "Feb", "Jan", "April", "Feb"})
Dim lstNew As IEnumerable(Of String) = Nothing
We will be printing the results on the console using a simple method shown here:
C#
static void PrintList(IEnumerable<string> str)
{
    foreach (var s in str)
        Console.WriteLine(s);
    Console.WriteLine("-------------");
}
VB.NET
Shared Sub PrintList(ByVal str As IEnumerable(Of String))
      For Each s In str
            Console.WriteLine(s)
      Next s
      Console.WriteLine("-------------")
End Sub
Let us get started.
1. Display common elements between two List<string>
 
Use the Enumerable.Intersect method
C#
// Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);
VB.NET
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)
OUTPUT
January_March
2. Display elements found in one List<string> but not in the other
 
Use the Enumerable.Except method
C#
// Compare two List<string> and display items of lstOne not in lstTwo
lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);
VB.NET
lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)
Note: The StringComparer.OrdinalIgnoreCase performs a case-insensitive ordinal string comparison
OUTPUT
February
3. Display distinct elements from a List<string>
 
Use the Enumerable.Distinct method
C#
// Unique List<string>
lstNew = lstFour.Distinct(StringComparer.OrdinalIgnoreCase);
PrintList(lstNew)
VB.NET
lstNew = lstFour.Distinct(StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)
OUTPUT
Jan_Feb_April
4. Convert all elements of a List<string> to UpperCase
 
Use the List.ConvertAll method
C#
// Convert elements of List<string> to Upper Case
lstNew = lstOne.ConvertAll(x => x.ToUpper());
PrintList(lstNew);
VB.NET
lstNew = lstOne.ConvertAll(Function(x) x.ToUpper())
PrintList(lstNew)
OUTPUT
MonthsInCaps
5. Concatenate and Sort two List<string>
 
Use the Enumerable.Concat method
C#
// Concatenate and Sort two List<string>
lstNew = lstOne.Concat(lstTwo).OrderBy(s => s);
PrintList(lstNew);
VB.NET
lstNew = lstOne.Concat(lstTwo).OrderBy(Function(s) s)
PrintList(lstNew)
OUTPUT
AtoM
6. Concatenate Unique Elements of two List<string>
 
C#
// Concatenate Unique Elements of two List<string>
lstNew = lstOne.Concat(lstTwo).Distinct();
PrintList(lstNew);
VB.NET
lstNew = lstOne.Concat(lstTwo).Distinct()
PrintList(lstNew)
OUTPUT
JtoA
7. Reverse a List<string>
 
Use the List.Reverse method
C#
// Reverse a List<string>
lstOne.Reverse();
PrintList(lstOne);
VB.NET
lstOne.Reverse()
PrintList(lstOne)
OUTPUT
MtoJ
8. Search a List<string> and Remove the Search Item from the List<string>
Use the List.RemoveAll method
C#
// Search a List<string> and Remove the Search Item
// from the List<string>
int cnt = lstFour.RemoveAll(x => x.Contains("Feb"));
Console.WriteLine("{0} items removed", cnt);
PrintList(lstFour);
VB.NET
Dim cnt As Integer = lstFour.RemoveAll(Function(x) x.Contains("Feb"))
Console.WriteLine("{0} items removed", cnt)
PrintList(lstFour)
OUTPUT
ItmesRemoved
So these were some common List<string> operations. In the next article[UPDATE: The article is online Some Common Operations using List<string> - Part II], we will see some more advanced operations on the List<string>. Stay tuned! The entire source code of this article can be downloaded over here
I hope you liked this article and I thank you for viewing it.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Jaipee on Saturday, January 16, 2010 12:00 AM
Very useful stuff
Comment posted by Tareq Saleh on Sunday, January 17, 2010 2:51 AM
Thanks for this article .

Please check the note (OrdinalIgnoreCase = a case-insensitive  not case-sensitive)
Comment posted by Suprotim Agarwal on Sunday, January 17, 2010 3:00 AM
Tareq: Thanks! That was a typo and has been rectified.
Comment posted by Himansu Nayak on Wednesday, December 19, 2012 3:08 AM
It is really a good stuff and very useful.

Thank you very much for this article.
Comment posted by Jamison White on Thursday, July 31, 2014 10:51 AM
You can use the FROM keyword instead of string array.
Replace:
Dim lstOne As New List(Of String) (New String() {"January", "February", "March"})

With:
Dim lstOne As New List(Of String) FROM {"January", "February", "March"}