1

Say I have the code below:

dynamic myData = GetMyData();
foreach(dynamic d in myData.data)
{
   Console.WriteLine(d.name);
}

How could I writeout all of the names in alphabetical order? If I were using something like List<MyClass> i would just use myData.OrderBy(t => t.name), but this does not seem to work when I'm using a dynamic type.

Any suggestions to how I can order these values?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 2
    Why are you using dynamic at all? What's wrong with `var myData = GetMyData().OrderBy(t => t.name);`? – Tim Schmelter Jun 01 '12 at 21:53
  • 1
    I am using the Facebook C# SDK and the examples they give all make use of `dynamic`. This is my first exposure to `dynamic` types, so I can't speak intelligently about why or why not they should be used in this situation. To be honest I'm not quite sure how dynamic and anonymous types differ, but that's a whole different post. I do plan on researching the subject some more, but for now I'd just like to know if this can be done. If not, no big deal. – Abe Miessler Jun 01 '12 at 21:55
  • possible duplicate of [Extension method and dynamic object in c#](http://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object-in-c-sharp) – nawfal Jul 19 '14 at 21:02

2 Answers2

7
Enumerable.OrderBy(myData, (Func<dynamic, dynamic>)(t => t.name));

That should return the same as myData.OrderBy(t => t.name) would normally.

Since OrderBy is an extension method, it won't work on dynamic types. See this answer.

Community
  • 1
  • 1
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • 1
    Trying that causes this error: "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type" – Paul Phillips Jun 01 '12 at 21:54
  • 1
    I added a cast. See if it helps. – Kendall Frey Jun 01 '12 at 21:58
  • Now it gives a `RuntimeBinder` exception: "The best overloaded method match for 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' has some invalid arguments" – Paul Phillips Jun 01 '12 at 22:01
  • Are you absolutely sure `t` has a `name` property? (case-sensitive) I tested with a list of strings, and the `Length` property worked. – Kendall Frey Jun 01 '12 at 22:02
  • My mistake, you are correct. I had structured it exactly like the OP and forgot to remove the `.data` from `mydata` – Paul Phillips Jun 01 '12 at 22:04
3

This might work for you:

IEnumerable<dynamic> sequence = Enumerable.Cast<dynamic>(myData);
foreach (var result in sequence.OrderBy(x => x.name))
{
    Console.WriteLine(result.name);
}

Basically after the call to Cast<dynamic> and the conversion to IEnumerable<dynamic>, you can do what you like as a sequence rather than a single value.

Not that I've actually tried the above, but I believe it should work.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194