动态表达式LINQ Select-从嵌套集合中选择很多

时间:2018-10-17 13:11:45

标签: c# linq dynamic-linq

Dynamic Expressions Docs

将此示例类结构考虑在内-

public class Apprentice
{
    public Guid Id { get; set; }
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public virtual ICollection<ApprenticeAddress> Addresses { get; set; }
}

public class ApprenticeAddress
{
    public Guid Id { get; set; }
    public Guid ApprenticeId { get; set; }
    public virtual Apprentice Apprentice { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string Town { get; set; }
    public Guid CountyId { get; set; }
    public virtual County County { get; set; }
    public string PostCode { get; set; }
    public bool IsPrimaryAddress { get; set; }
    public Guid AddressTypeId { get; set; }
    public virtual AddressType AddressType { get; set; }
}

基于上面提供的文档和示例类结构,我一直在努力编译动态选择器来选择运行时未知的随机属性。我遇到的主要问题是选择链接到返回的学徒的任何地址的 AddressLine1 属性。

此示例LINQ select将执行我需要执行的操作,但是谁能帮助将其转换为数据对象初始值设定项字符串?

var r = repo.GetAll().ToList().Select(x =>
        new
        {
            x.FamilyName,
            addresses = x.Addresses.SelectMany(y => y.AddressLine1)
        });

更新

如果我使用下面的代码和数据对象初始化程序字符串传递到Select扩展方法中,则会得到所需的匿名对象-

var whereTxt = "Active";
var selectTxt = "new (GivenName AS GivenName,FamilyName AS FamilyName)";
var repo = Storage.DataContext.GetRepository<Apprentice>();
return repo.GetAll().Where(whereTxt).Select(selectTxt).AsQueryable();

我遇到的问题是确定从嵌套集合中检索特定属性(运行时未知)的语法

1 个答案:

答案 0 :(得分:1)

可以使用System.Linq.Dynamic.Core轻松完成此操作:

var data = new[]
{
    new Apprentice { FamilyName = "f", Addresses = new [] { new ApprenticeAddress { AddressLine1 = "address x" }, new ApprenticeAddress { AddressLine1 = "address y" } } }
}.AsQueryable();

var result = data.Select(x => new { x.FamilyName, Addresses = x.Addresses.Select(y => y.AddressLine1) });
Console.WriteLine("result: " + JsonConvert.SerializeObject(result, Formatting.Indented));

var resultDynamic = data.Select("new (FamilyName as FamilyName, Addresses.Select(AddressLine1) as Addresses)");
Console.WriteLine("resultDynamic: " + JsonConvert.SerializeObject(resultDynamic, Formatting.Indented));

有关完整的工作示例,请参见https://github.com/StefH/System.Linq.Dynamic.Core.TestApps中的ConsoleApp2

请注意,Addresses.SelectMany(y => y.AddressLine1)是错误的,这将从地址中选择字符。