开发者

Replace function call with anonymous method

I feel stupid. Can you guys help me to replace GetCamp(x) with anonymous?

This code:

   aspnet_Users.ForEach(x =>
        {
            usersVm.Add(new User{
                 Camp = Mapper.Map<DbCamp, Camp>(GetCamp(x)),
            });
        }); 


    private DbCamp GetCamp(aspnet_Users x)
    {
        //... some code ...
        return someDbCamp;
    }

Should be something li开发者_StackOverflow社区ke this:

   aspnet_Users.ForEach(x =>
    {
         usersVm.Add(new User{
              Camp = Mapper.Map<DbCamp, Camp>
              (
                    Func<DbCamp>(aspnet_Users u) => 
                    { 
                         //... some code ...
                          return someDbCamp;
                    }
               ),
           });
     }); 

That doesn't work because Mapper.Map<Database.Camp, Camp> expects an object typeof(DbCamp) as a parameter, not a delegate. I can use a normal function of course but from academical standpoint, I wonder if it's possible to use anonymous method here.


I think this should handle the empty case.

x => x.Users.Any() ? x.Users.First().Camp : null

In context:

_dataContext.aspnet_Users.ToList().ForEach(x =>
    {
        usersVm.Add(new User{
             Camp = Mapper.Map<Database.Camp, Camp>(
                  x => x.Users.Any() ? x.Users.First().Camp : null),
        });
    }); 


Does this not work:

x => GetCamp(x)

?


aspnet_Users.ForEach(x =>
{
    usersVm.Add(new User{ Camp = Mapper.Map<DbCamp, Camp>({ /*... some code using x ...*/ return someDbCamp; }) });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜