将自定义列表值复制到var或dynamic并循环?

时间:2011-06-22 19:38:36

标签: c# list c#-4.0 objectdatasource

在我的objectdatasource中,我使用_selected事件从列表中获取一些值,该对象返回。

所以我正在使用e.Returnvalue

protected void ObjTrailerList_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {

        dynamic details = e.ReturnValue;
       var d = e.ReturnValue;}

现在我想将整个自定义列表值复制到var或dynamic n遍历。 怎么做?我不想创建MovieTrailers的对象List并将其复制到其中。

我的自定义列表是

public class MovieTrailers
{
   public int? TrailerId
   {
       get;
       set;
   }
   public string MovieName
   {
       get;
       set;
   }
   public string TrailerUrl
   {
       get;
       set;
   }
}

1 个答案:

答案 0 :(得分:1)

private static void TestDynamic(dynamic list)
{
    foreach (var item in list)
    {
        if (item is string)
        {
            string foo = item;//use it as string
            Console.WriteLine("The string is: {0}", foo);
        }
        else
        {
            Console.WriteLine(item);
        }
    }
}

static void Mian()
{
    //pass a list of strings
    TestDynamic(new List<string> { "Foo", "Bar", "Baz" });

    //pass a list of anonymous class
    TestDynamic(new List<dynamic> { new { Age = 25, BirthDay = new DateTime(1986, 1, 3) }, new { Age = 0, BirthDay = DateTime.Now } });

    //TestDynamic(25);//this will cause exception at run time at the foreach line
}


//output:
The string is: Foo
The string is: Bar
The string is: Baz
{ Age = 25, BirthDay = 3/1/1986 00:00:00 }
{ Age = 0, BirthDay = 23/6/2011 01:23:18 }