[dba-VB] A couple of code snippets...

Salakhetdinov Shamil mcp2004 at mail.ru
Thu Apr 26 18:28:25 CDT 2012


Hi All --

Just wanted to share a couple of test code samples I've got written here while working on real life development task.
Please review, comment, remark, write your own versions.

Test 1
=====

public void TestSort()
{
    // simulate reading products' .csv file into text string
    StringBuilder text = new StringBuilder()
        .AppendLine("P1|12.34").AppendLine("P2|5.28").AppendLine("P3|21.74")
        .AppendLine("P4|67.12").AppendLine("P5|23.98");

    // parse text string and add parsed items n into an array list
    ArrayList products = new ArrayList();
    foreach (string textLine in text.ToString().Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
    {
        products.Add(new { Name = textLine.Substring(0, 2), Price = Decimal.Parse(textLine.Substring(3)) });
    }

    // print sorted products list
    foreach (var product in (from p in products.Cast<dynamic>().OrderBy(x => x.Price) select p))
    {
        System.Console.WriteLine(product);
    }
}

Test 2 (Test 1 variation using yield return)
================================

public void TestSort2()
{
    // print sorted products list
    foreach (var product in (from p in GetProducts().OrderBy(x => x.Price) select p))
    {
        System.Console.WriteLine(product);
    }
}

public IEnumerable<dynamic> GetProducts()
{
    // simulate reading products' .csv file into text string
    StringBuilder text = new StringBuilder()
        .AppendLine("P1|12.34").AppendLine("P2|5.28").AppendLine("P3|21.74")
        .AppendLine("P4|67.12").AppendLine("P5|23.98");

    // parse text string and add parsed item to IEnumerable<dynamic> using yield return
    foreach (string textLine in text.ToString().Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
    {
        yield return new { Name = textLine.Substring(0, 2), Price = Decimal.Parse(textLine.Substring(3)) };
    }
}

Thank you.

-- Shamil



More information about the dba-VB mailing list