Some Common Operations using List - Part II

Posted by: Suprotim Agarwal , on 1/17/2010, in Category LINQ
Views: 114626
Abstract: In Part I of this article, I shared some common operations on List. In this article, I will share some advanced examples that demonstrate common operations on List
Some Common Operations using List<string> - Part II
 
In Part I of this article, I shared some common operations on List<string>. You can read the article over here Some Common Operations using List - Part I. In this article, I will share some more examples that demonstrate common operations on List<string>
Here are the sample List<string> declarations for demonstration purposes. The VB.NET code has been converted using a conversion tool and 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. Order the elements of a List<string> first by Length and then by words
 
C#
// Order by Length then by words (descending)
lstNew = lstThree.OrderBy(x => x.Length)
        .ThenByDescending(x => x);
PrintList(lstNew);
VB.NET
lstNew = lstThree.OrderBy(Function(x) x.Length).ThenByDescending(Function(x) x)
PrintList(lstNew)
OUTPUT
MtoJ
2. Create a new string by combining all words of a List<string>
 
Use the Enumerable.Aggregate method
C#
// Create a string by combining all words of a List<string>
// Use StringBuilder if you want performance
string delim = ",";
var str = lstOne.Aggregate((x, y) => x + delim + y);
Console.WriteLine(str);
Console.WriteLine("-------------");
VB.NET
Dim delim As String = ","
Dim str = lstOne.Aggregate(Function(x, y) x & delim & y)
Console.WriteLine(str)
Console.WriteLine("-------------")
Note: You should use a StringBuilder for performance
OUTPUT
SingleLineJtoM
3. Create a List<string> from a Delimited string
 
Split the string and use the Enumerable.ToList method
C#
// Create a List<string> from a Delimited string
string s = "January February March";
char separator = ' ';
lstNew = s.Split(separator).ToList();
PrintList(lstNew);
VB.NET
Dim s As String = "January February March"
Dim separator As Char = " "c
lstNew = s.Split(separator).ToList()
PrintList(lstNew)
OUTPUT
JtoM
4. Convert a List<int> to List<string>
 
Use the List(T).ConvertAll method
C#
// Convert a List<int> to List<string>
List<int> lstNum = new List<int>(new int[] { 3, 6, 7, 9 });
lstNew = lstNum.ConvertAll<string>(delegate(int i)
{
   return i.ToString();
});
PrintList(lstNew);
VB.NET
Dim lstNum As New List(Of Integer)(New Integer() { 3, 6, 7, 9 })
lstNew = lstNum.ConvertAll(Of String)(Function(i As Integer) i.ToString())
PrintList(lstNew)
OUTPUT
Numbers
5. Count Repeated Words in a List<string>
 
C#
// Count Repeated Words
var q = lstFour.GroupBy(x => x)
   .Select(g => new { Value = g.Key, Count = g.Count() })
   .OrderByDescending(x => x.Count);
 
foreach (var x in q)
{
   Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
VB.NET
Dim q = lstFour.GroupBy(Function(x) x).Select(Function(g) New With {Key .Value = g.Key, Key .Count = g.Count()}).OrderByDescending(Function(x) x.Count)
 
For Each x In q
   Console.WriteLine("Value: " & x.Value & " Count: " & x.Count)
Next x
OUTPUT
ValueandMonth
These were some more List<string> operations. The entire source code of this article can be downloaded over here. You can also read the first part of this article over here Some Common Operations using List - Part I.
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 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 eBook 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 the 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 ten consecutive times. 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 John Bubriski on Thursday, January 21, 2010 10:08 AM
Here is shorthand for converting the List<int> to List<string>:

var lstNum = new List<int> { 3, 6, 7, 9 };
var lstNew = lstNum.ConvertAll<string>(i => i.ToString());

You don't need the whole delegate syntax, nor do you need to create an array of integers to pass to the list.  You can use the array initialization syntax with Lists.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook