【问题标题】:Dynamic Expressions LINQ Select - SelectMany from nested collection动态表达式 LINQ 选择 - 嵌套集合中的 SelectMany
【发布时间】:2018-10-21 16:53:25
【问题描述】:

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();

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

【问题讨论】:

  • 你能举个例子,在“数据对象初始化字符串”下你到底理解了什么?如果你得到了你想要的匿名对象,问题到底出在哪里?
  • 我遇到的问题是我希望选择的属性在运行时是未知的,我必须通过字符串选择器创建选择语句。我无法弄清楚在嵌套集合上选择属性的语法。我已经更新了这个问题,以展示我的意思的一个例子。

标签: c# linq dynamic-linq


【解决方案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 =&gt; y.AddressLine1)是错误的,这会选择地址中的字符。

【讨论】:

  • 非常感谢 - 我非常接近,但没有使用 System.Linq.Dynamic.Core!
猜你喜欢
  • 2021-10-11
  • 2012-01-11
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
相关资源
最近更新 更多