Archive

Posts Tagged ‘Generics’

The Case Against Count Method in LINQ

September 22, 2010 Leave a comment

The Count method in LINQ is really slow as it iterates of all the items and adds a tally unless the IEnumerator is really an ICollection.

If you need to know whether there is at least 1 item use Any method as it traverses through and if there is an item it exists returning true.

So if you have a huge list the performance difference will be large.

public static int Count(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<T> is2 = source as ICollection<T>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

public static bool Any(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            return true;
        }
    }
    return false;
}

The source code from LINQ pretty much spells it out. 🙂

Blair…

Advertisements

Generics and Reflection .NET with C#

July 24, 2010 Leave a comment

Generics in .NET work a little differently depending that normal reflection over types. The difference appears in whether the type is an open type, no type arguments supplied or a closed type all type arguments supplied.

static void Main()
        {
            Type opentype = typeof (List<>);
            
            Console.WriteLine("Name: " + opentype.FullName);
            Console.WriteLine("Is Generic Type: " + opentype.IsGenericType);
            Console.WriteLine("Contains Generic Parameters: " + opentype.ContainsGenericParameters);

            Console.WriteLine();

            Type closedtype = typeof(List<Person>);

            Console.WriteLine("Name: " + closedtype.FullName);
            Console.WriteLine("Is Generic Type: " + closedtype.IsGenericType);
            Console.WriteLine("Contains Generic Parameters: " + closedtype.ContainsGenericParameters);
            Console.WriteLine("Type Arguments are as follows...");
            Array.ForEach(closedtype.GetGenericArguments(), Console.WriteLine);

            Console.ReadKey();
        }

The output is as follows..
Name: System.Collections.Generic.List`1
Is Generic Type: True
Contains Generic Parameters: True
Name: System.Collections.Generic.List`1[[CSharpSamples.Person, CSharpSamples, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
Is Generic Type: True
Contains Generic Parameters: False
Type Arguments are as follows…
CSharpSamples.Person

The first line shows System.Collections.Generic.List`1, which means there is 1 type parameters. This is also an open type as Person has not been supplied as a type argument as opposed to System.Collections.Generic.List`1[[CSharpSamples.Person, CSharpSamples, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

Also the type is generics as show by the second line and contain un supplied type arguments as shown on the third line.

The final line GetGenericArguments() allows you to get all supplied type arguments.

Hope this helps…

Blair

Anonymous Types and Generics

February 11, 2010 Leave a comment

Trying to use anonymous type with Generics is just a pain. Going to download VS 2010 and see if the dynmaic type helps.

Check this code out. Its a major headache….

using System;
using System.Collections.Generic;


namespace AnonymousTypesAndCollections
{


    class Program
    {
        static void Main(string[] args)
        {
            var customer = new
                               {
                                   Id = 1,
                                   Name = "Blair Davidson"
                               };

            Type openGenericType = typeof(List<>);
            Type closedGenericType = openGenericType.MakeGenericType(customer.GetType());

            object list = Activator.CreateInstance(closedGenericType);

            closedGenericType.GetMethod("Add").Invoke(list, new[] {customer});
            Console.WriteLine("Count: {0}",closedGenericType.GetProperty("Count").GetGetMethod().Invoke(list,null));

            Console.WriteLine(closedGenericType.FullName);
            Console.ReadKey();
        }
    }
}

Anyone know another way to do this?

Categories: Development Tags: , , ,