Order List Of Anonymous Type

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
 
K

kndg

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Join 3
Generics 7
Problem in method ElementAt using reflection 10
ToString and FromString 10
Parsing Data Problem ... 5
Change ToDictionary to ToList 1
Get Mime Type of File 4
Count 4

Top