如何将属性选择器的字符串表示形式转换为lambda表达式?
输入的格式为:
"Child.Name"我需要将其转换为要在OrderBy子句中使用的谓词;
query.OrderBy(x => x.Child.FirstOrDefault().Name);如果属性不是集合,是否也有可能有一个解决方案,例如,针对标准属性或字段进行工作;
"Quantity"将创建一个谓词,例如;
x => x.Quantity编辑:
尝试改写上面的问题,如果我可以修改输入字符串,是否可以执行;
"Child.FirstOrDefault().Name"作为
x => x.Child.FirstOrDefault().Name在OrderBy中?
发布于 2014-11-06 00:00:06
我认为您首先需要使用Activator类型按名称获取类的实例:
var child = System.Activator.CreateInstance(Type.GetType("Assembly", "Child"));然后,您可以使用GetProperty按名称获取属性
var childType = (typeof)child;
var name = childType.GetProperty("Name");然后您可以将这些类型传递给您的查询。
或者,您可以使用the LINQ Predicate Builder library。
发布于 2014-11-06 16:53:45
有一个应用程序可以解决您的问题。试试看,告诉我一些事情。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicación.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
List<Parent> Parents = new List<Parent>();
List<Parent> orderedParents = Parents.Cast<Parent>().OrderBy(x => x.Cast<Child>().Select(y => y.myName)).ToList();
}
}
public class Parent: IQueryable
{
List<Child> child = new List<Child>();
#region Miembros de IQueryable
public Type ElementType
{
get { throw new NotImplementedException(); }
}
public System.Linq.Expressions.Expression Expression
{
get { throw new NotImplementedException(); }
}
public IQueryProvider Provider
{
get { throw new NotImplementedException(); }
}
#endregion
#region Miembros de IEnumerable
public System.Collections.IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
public class Child: Parent
{
public string myName;
}
}发布于 2014-11-06 21:29:02
下面将返回集合上属性的字符串值:
string propertyValue = source.GetType()
.GetProperty(stringProperty)
.GetValue(query.FirstOrDefault(), null) as string;https://stackoverflow.com/questions/26761330
复制相似问题