DotNetCurry Logo

Some Common Operations using List - Part II

Posted by: Suprotim Agarwal , on 1/17/2010, in Category LINQ
Views: 105810
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
  • Please Share this article if you think it was worth reading. Thanks!
Further Reading - Articles You May Like!
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 a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
comments powered by Disqus
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.