C# 动态表达式LINQ Select-从嵌套集合中选择多个
考虑到这个示例类结构-C# 动态表达式LINQ Select-从嵌套集合中选择多个,c#,linq,dynamic-linq,C#,Linq,Dynamic Linq,考虑到这个示例类结构- 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 clas
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; }
}
更新
如果我使用下面的代码和数据对象初始值设定项字符串传递到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();
var whereTxt=“活动”;
var selectTxt=“新建(GivenName作为GivenName,FamilyName作为FamilyName)”;
var repo=Storage.DataContext.GetRepository();
返回repo.GetAll().Where(whereTxt).Select(selectTxt.AsQueryable();
我遇到的问题是确定从嵌套集合中检索特定属性(运行时未知)的语法这可以通过以下方法轻松完成: 有关完整的工作示例,请参阅中的
ConsoleApp2
请注意,
地址。SelectMany(y=>y.AddressLine1)
是错误的,这会从地址中选择字符。您能举一个例子,在“数据对象初始值设定项字符串”下您到底理解什么?如果您得到了想要的匿名对象,那么问题到底出在哪里?我的问题是,我希望选择的属性在运行时是未知的,我必须通过字符串选择器创建select语句。我无法理解在嵌套集合上选择属性的语法。我已经更新了这个问题,以展示我的意思。非常感谢-我非常接近这个问题,但没有使用System.Linq.Dynamic.Core!
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();
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));