web 2.0

Anonymous Type Collection with C# 3.5

Hi,

Today i'll talking about a new Collection Type i've developped named AnonymousCollection in order to store C# Anonymous Types.

It's a begining so i would be pretty happy to get some feedbacks about that so as to make it better :)

First of all here is the AnonymousCollection implementation

I used some Reflection with TypeDescriptor and PropertyDescriptor to get Properties of the AnonymousType.

public class AnonymousCollectionItem
{
    public IDictionary<String, Object> Values
    {
        get;
        private set;
    }

    public AnonymousCollectionItem()
    {
        Values = new Dictionary<String, Object>();
    }
    public void Add(Object o)
    {
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(o))
        {
            Object val = property.GetValue(o);
            Values.Add(property.Name, val);
        }
    }
    public Object GetValue(String key)
    {
        return Values[key];
    }
    public void SetValue(String key, Object val)
    {
        Values[key] = val;
    }
}
public class AnonymousCollection : List<AnonymousCollectionItem>
{
    public new void Add(AnonymousCollectionItem item)
    {
        base.Add(item);
    }
    public void Add(Object o)
    {
        AnonymousCollectionItem item = new AnonymousCollectionItem();
        item.Add(o);
        base.Add(item);
    }
}

And the usage of my Collection

class Program
{
    static void Main(string[] args)
    {
        // Add Elements To Collection
        AnonymousCollection col = new AnonymousCollection();
        for (int i = 0; i < 5; i++)
        {
            var myType = new { ID = i, FirstName = "Scott", Email = "foo@foo.com" };
            // Standard Add Method
            col.Add(myType);

            // Using Newly created AnonymousCollectionItem element
            AnonymousCollectionItem item = new AnonymousCollectionItem();
            item.Add(myType);
            col.Add(item);
        }

        // Display All Collection Elements
        foreach (var item in col)
        {
            foreach (var o in item.Values)
            {
                Console.WriteLine(o.ToString());
            }
        }

        // Change One Element Value
        col[0].SetValue("FirstName", "BLAH");
        Console.WriteLine(col[0].GetValue("FirstName"));
    }
}

Thanks in advance, hope this help's.

Stay Tuned !



Views(2685)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile