ForEach on IEnumerable <dynamic> type data </dynamic>

时间:2013-02-15 20:40:56

标签: c# dynamic ienumerable

我以以下形式获取数据:

 [0]: { rkey = "100asb", pkey = "100ap0", ckey = {1/6/2013 3:28:09 AM} }
 [1]: { rkey = "yxq4c", pkey = "100iis", ckey = {1/6/2013 6:38:48 PM} }
  .
  .
  .

我必须编写另一种可以访问值rkeypkeyckey的方法。很遗憾,我无法以线性ForEachParallel.ForEach访问它们。我已经搜索过了,但是我还没有找到访问我的参数的解决方案。有人建议将其转换为Dictionary,但我不确定这是否是一条好路。它必须比那简单得多。

我写的代码是这样的:

var films = myrollup.GetCompletedMovies(dtstart, dtend).Result;

using (var session = factory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {

        Parallel.ForEach(films, currentFilm =>
        {
            dynamic f = currentFilm;
            lock (myrollup)
            {
                var user = User.GetAsync(f.pkey).Result;
                var record = new FilmAnalytics()
                {
                    UserID = currentFilm.pkey,
                    FilmID = currentFilm.rkey,
                    UserName = user.FirstName,
                    UserLastName = user.LastName,
                    UserAlias = user.Alias,
                    UserEmail = user.Email,
                    UserFacebook = user.FbEmail,
                    Dateofcompletion = currentFilm.ckey
                };
                session.SaveOrUpdate(record);
            }
        });

        transaction.Commit();
    }
}

变量films生成IEnumerable<dynamic>类型数据。

2 个答案:

答案 0 :(得分:1)

适合我:

static void Main(string[] args) {
    IEnumerable<dynamic> films = new dynamic[] { new { rkey = 1, rval = "val1" }, new { rkey = 2, rval = "val2" } };

    foreach (var film in films.Select(f => new { RKey = (int)f.rkey,RValue = (string)f.rval }))
        Console.WriteLine(film.RKey + ":" + film.RValue);
}

这样我可以将动力学转换为强类型对象,然后我可以随心所欲地做任何事情

答案 1 :(得分:0)

您必须创建一个类

 public class Thing
    {
        public string rkey { get; set; }
        public string pkey { get; set; }
        public DateTime ckey { get; set; }
    }

然后像这样完成任务:

public Task<IEnumerable<Thing>> ....

然后我可以访问pkey,rkey和ckey。