Order List Of Anonymous Type

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have the following List of an anonymous type:

IList<Object> data = new List<Object>();
data.Add(new { Type = "A", Value = 10 });
data.OrderBy(r => r.Type);

However, I am not able to order it because type is not recognized on
r.Type.

What am I doing wrong?

Thank You,

Miguel
 
Hello,

I have the following List of an anonymous type:

IList<Object> data = new List<Object>();
data.Add(new { Type = "A", Value = 10 });
data.OrderBy(r => r.Type);

However, I am not able to order it because type is not recognized on
r.Type.

What am I doing wrong?

Your list is of type "Object" and "Object" doesn't have the property
named "Type".
Solution: Just declare your type explicitly (don't use anonymous type).

Or, if you know all the items in your list before hand, you could use
array instead,

var data = new[]
{
new { Type = "A", Value = 10 },
new { Type = "C", Value = 30 },
new { Type = "B", Value = 20 },
};

var sorted = data.OrderBy(r => r.Type);

foreach (var item in sorted)
{
Console.WriteLine("Type: {0}, Value: {1}", item.Type, item.Value);
}

Or, if you're using C#4.0, you can use dynamic instead of object

IList<dynamic> data = new List<dynamic>();
data.Add(new { Type = "A", Value = 10 });
data.Add(new { Type = "C", Value = 30 });
data.Add(new { Type = "B", Value = 20 });

var sorted = data.OrderBy(r => r.Type);

foreach (var item in sorted)
{
Console.WriteLine("Type: {0}, Value: {1}", item.Type, item.Value);
}

Regards.
 
Back
Top