在LINQ查询中调用自定义方法 [英] Calling a custom method in LINQ query

查看:156
本文介绍了在LINQ查询中调用自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的查询:

 var q = 
        from u in db.User
        select new
        {
            userId = u.UserId,
            userName = o.Name,
            userAvatar = o.AvatarCode
        };

然后,我必须将 AvatarCode 转换为 AvatarPath 使用自定义静态方法 Image.GetPath

Then, I have to transform AvatarCode to AvatarPath using custom static method Image.GetPath.

可以通过以下方式进行设置:

It's possible to make this in the following way:

 var q = 
        (from u in db.User
        select new
        {
            userId = u.UserId,
            userName = o.Name,
            userAvatar = o.AvatarCode
        })
        .AsEnumerable()
        .Select(new
        {
            userId = u.UserId,
            userName = o.Name,
            userAvatar = Image.GetPath(o.AvatarCode)
        };

但是如果对象字段的数量很大,那么在第二个选择中复制所有字段是一个过分。

But if the number of object fields is large then it's an overkill to duplicate all fields in the second Select.

有没有其他选择?

例如,一些方法来标记应该执行的方法查询执行离子:

For example, some approach to mark methods that should be executed after query execution:

 var q = 
        from u in db.User
        select new
        {
            userId = u.UserId,
            userName = o.Name,
            userAvatar = Linq.ExecuteLater(Image.GetPath(o.AvatarCode))
        };


推荐答案

没有任何这样的方法,但如果问题是只能在第二次选择中再次指定的字段数量可以这样做:

There is not any such method but if the problem is only number of fields which must be specified again in the second select you can do something like this:

var q = 
    (from u in db.User
    select new
    {
        userId = u.UserId,
        userName = u.Name,
        userAvatar = u.AvatarCode
    })
    .AsEnumerable()
    .Select(u => new
    {
        User = u,
        Path = Image.GetPath(u.AvatarCode)
    });

这篇关于在LINQ查询中调用自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆