使用Dynamic Linq Select表达式的构造函数调用

本文关键字:函数调用 表达式 Dynamic Linq Select 使用 | 更新日期: 2023-09-27 18:19:38

我使用的是Dynamic Linq。

我可以做以下事情:

IQueryable<Person>().Select("new(Id as Id, FirstName + Surname as Name");

这将创建一个包含匿名类型的IQueryable而不是IQueryable<object>)。

但考虑到我有以下课程:

public class ListItem
{
    public ListItem()
    {
    }
    public ListItem(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
    public int Id { get; set; }
    public string Name { get; set; }
}

我想通过调用ListItem的构造函数,直接从我的IQueryable<Person>中选择这种类型,相当于以下内容:

IQueryable<Person>().Select(p => new ListItem(p.Id, p.FirstName + p.Surname));

我尝试过以下变体:

// Illegal - new expects form "new()" - exception "'(' expected"
IQueryable<Person>().Select("new ListItem(Id, FirstName + Surname)");
// this doesn't work, "No property 'ListItem' exists on type 'Person'"
IQueryable<Person>().Select("ListItem(Id, FirstName + Surname)");
// this doesn't work because "[" is not expected
IQueryable<Person>().Select("[MyProject.Utils.ListItem,MyProject]()");

我相信,从这里提供的文件来看,这是可能的:

方法、构造函数和索引器的重载解析使用类似于C#的规则。在非正式术语中,重载解析将选择最佳匹配方法、构造函数或索引器,或者在无法识别单个最佳匹配的情况下报告模糊性错误。

请注意,构造函数调用没有以new作为前缀。

这可能吗?或者我误解了文件?

使用Dynamic Linq Select表达式的构造函数调用

我不确定Dynamic Linq中的Select方法是否支持构造函数。也许文档中说这只支持谓词,比如Where方法中使用的表达式。不过我不确定。

无论如何,这可能是一个解决方案:

var result =
    context
        .Customers
        .Select("new(Id as Id, FirstName + Surname as Name")
        .AsEnumerable()
        .Select(x => new ListItem(x.Id, x.Name))
        .ToList();