Creating an Empty List<AnonymousType>

This post is written by guest blogger Albin Sunnanbo. He’s a great friend and source of inspiration and also one of the best developers I know. It was Albin that first introduced me to LINQ, EF Migrations and jQuery that I now use daily.

Sometimes you use Tuple<T1, T2> in C# to store results of temporary calculations, like in the following example:

var testDataValues = new int[] { 0, 1, 2 };
 
var okResults = new List<int>();
var failedArgumentsWithError = new List<Tuple<int, string>>();
foreach (var value in testDataValues)
{
    try
    {
        var result = CalculateResult(value);
        okResults.Add(result);
    }
    catch (Exception ex)
    {
        failedArgumentsWithError.Add(Tuple.Create(value, ex.Message));
    }
}
 
foreach (var failedArgumentWithError in failedArgumentsWithError)
{
    Console.WriteLine(failedArgumentWithError.Item1 + " failed with error: " +
                      failedArgumentWithError.Item2);
}

 
The Tuple<T1, T2> however is not really good for readability, the naming of Item1, Item2, etc. does not reveal the intention of the properties. When storing temporary results like this in a method there is usually better to use an anonymous type. However to declare a list of an anonymous type you need to use a little trick with yield break.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.