Some Common Operations using List - Part II

Posted by: Suprotim Agarwal , on 1/17/2010, in Category LINQ
Views: 95232
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
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and authored a new one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel