从单个对象中选择作为表达式 [英] Selecting as expression from a single object

查看:58
本文介绍了从单个对象中选择作为表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将表达式应用于单个项目?现在,我有了一个可以在列表或任何支持Select扩展方法的集合上使用的表达式.我也想将该功能扩展到单个对象.这里有一个例子来阐明我的意思:

How can an expression be applied to a single item? Right now I have an expression that can be used on a list or any collection that supports the Select extension method. I would like to expand that functionality to single objects also. Here's an example to clarify what I mean:

private static readonly Expression<Func<Book, BookDto>> AsBookDto =
        x => new BookDto
        {
            Title = x.Title,
            Author = x.Author.Name,
            Genre = x.Genre,
            Description = x.Description,
            Price = x.Price,
            PublishDate = x.PublishDate
        }; 

使用此表达式,我可以执行以下操作:

With this expression I can do something like this:

IQueryable<BookDto> books = db.Books.Include(b => b.Author)
.Where(x => x.AuthorId == authorId).Select(AsBookDto);

我正在寻找一种可重用该Expression的方法,这样,当我收到包含作者在内的一本书时,我可以执行以下操作:

What I'm looking for is a way to reuse that Expression so that when in a method I receive a Book with author included I could do something like this:

public BookDto SampleMethod(Book propertiesIncludedBook)
{
    //this does not compile because Book does not have a Select method.
    return propertiesIncludedBook.Select(AsBookDto);
}

推荐答案

大多数LINQ扩展都在IEnumerableIQueryable上运行,在您的情况下,您只需要一个 normal 函数/委托,但是如果您要保留与LINQ相同的语法,只需为此编写自己的扩展方法:

Most of LINQ extensions work on IEnumerable or IQueryable, in your case what you need is just a normal function/delegate but if you want to keep same syntax you use with LINQ just write your own extension method for that:

public static TOutput SelectSingle<TInput, TOutput>(
    this TInput obj,
    Expression<Func<TInput, TOutput>> expression)
{
    return expression.Compile()(obj);
}

用作:

public BookDto SampleMethod(Book propertiesIncludedBook)
{
    return propertiesIncludedBook.SelectSingle(AsBookDto);
}

省略了错误检查,但是如您所见,直接像这样使用它并没有这样的好处:

Error checking is omitted but as you can see there is not such benefit to use it directly like this:

public BookDto SampleMethod(Book propertiesIncludedBook)
{
    return AsBookDto.Compile()(propertiesIncludedBook);
}

使用单独的Func<Book, BookDto>进行

Edit 替代表达式的定义很有用,但使表达式本身变得毫无用处.已删除.

Edit alternative splitting expression definition with a separate Func<Book, BookDto> works but makes expression itself pretty useless. Removed.

这篇关于从单个对象中选择作为表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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