![](/img/trans.png)
[英]Create dynamic LINQ expression for Select with FirstOrDefault inside
[英]Create a LINQ expression for SELECT sentence
我有这个LINQ查询,其中“新”句子创建了一个匿名类型 :
var query = from x in List
select new {x.Field1, x.Field2};
如何为以下内容动态构建LINQ表达式:
select new {x.Field1, x.Field2};
更多内容:
我们有一个List <Customer>,其中Customer具有属性A,B,C,D,E,F,G。
有时我们只需要返回一些属性:
首次通话返回:
select new {x.A, x.B}
第二次通话返回:
select new {x.C, x.D}
回报是动态的! 我在字符串数组中有属性的名称。
谢谢!
假设要检索的属性为CSV。 您应该可以使用它。
public static class ObjectExtensions
{
public static Dictionary<string,object> GetProperties(this object obj, string properties)
{
var propertyNames = properties.Split(',');
var result = new Dictionary<string, object>();
var type = obj.GetType();
foreach (var property in propertyNames)
{
var prop = type.GetProperty(property);
var value = prop.GetValue(obj);
result.Add(property, value);
}
return result;
}
}
它将键值对存储在字典中
用法将是。
var result = list.Select(p => p.GetProperties("Field1,Field2"));
JsonSerializer.CreateDefault().Serialize(Console.Out, result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.