[英]Dynamic properties in LINQ query
I'm trying to convert a complex domain model into a CSV format. 我正在尝试将复杂的域模型转换为CSV格式。 However the dynamic structure of the model is pushing my LINQ wizardry to its limit :)
但是模型的动态结构将我的LINQ向导推到了极限:)
The desired result should look something like the following. 所需的结果应类似于以下内容。 A header row, then data rows.
标题行,然后是数据行。 Note that some fields are empty and others have multiple.
请注意,某些字段为空,而其他字段则为多个。
PropA;RolenameA;RolenameB;RolenameC
123;username1,username2;username1;username2
321;;;username1
I wish to create a LINQ query which dynamically can add properties for each Role and then fill that property with the correct username(s). 我希望创建一个LINQ查询,该查询可以动态地为每个角色添加属性,然后用正确的用户名填充该属性。 I recognize that the header and the data must be in 2 different statements.
我认识到标题和数据必须在2个不同的语句中。
var result = new { "PropA", Roles.ForEach(x => x.Rolename) }
result += query.Select(x => new { x.PropA, x.UserRoles.ForEach(...) });
Is what I'm trying to do not possible with LINQ and I should do it "manually" with a dynamic object, or is there some black magic I need to learn :)? 是我要使用LINQ无法做到的,我应该用动态对象“手动”完成它,还是我需要学习一些黑魔法:)?
public class A
{
public int PropA { get; set; }
public IEnumerable<UserRole> UserRoles { get; set; }
}
public class UserRole
{
public Role Role { get; set; }
public User User { get; set; }
}
public class Role
{
public string Rolename { get; set; }
}
public class User
{
public string Username { get; set; }
}
I ended up doing it "manually" with an ExpandoObject. 我最终使用ExpandoObject进行了“手动”操作。
foreach (var item in items)
{
var obj = new ExpandoObject() as IDictionary<string, Object>;
obj.Add("PropA", item.PropA);
foreach (var role in roles)
{
obj.Add(role.Name,
String.Join(",", item.UserRole.Where(x => x.Role == role).Select(x => x.User.Name)));
}
// omitted...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.