Payam
Payam

Reputation: 751

ForEach on IEnumerable<dynamic> type data

I am getting data in the form of :

 [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} }
  .
  .
  .

I have to write another method that has access to the values rkey, pkey and ckey. Unfortunately I can't access them in a linear ForEach or Parallel.ForEach. I have searched, but I have not found a solution to access my parameters. Some people suggested to convert this to a Dictionary, but I am not sure if that is a good path to take. It has to be much simpler than that.

the code that I have written is like this:

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();
    }
}

The variable films produces the IEnumerable<dynamic> type data.

Upvotes: 0

Views: 4756

Answers (2)

Payam
Payam

Reputation: 751

You have to create a class like

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

and then make the task like this:

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

then I can have access to pkey, rkey, and ckey.

Upvotes: 0

dead_ant
dead_ant

Reputation: 125

Works for me:

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);
}

This way I can transform dynamics to strongly typed objects and then I can do whatever I want with them

Upvotes: 1

Related Questions