c# - .Where 语句中的 LINQ 动态字段

标签 c#

如何在where语句中使用动态字段名?

示例:我可以使用,

MyList.Where(x => x.Name == "MyName");

但是如何使用呢?

string MyField = "Name";
MyList.Where(x => MyField == "MyName");

最佳答案

您可以使用 System.Reflection 中的 PropertyInfo 并使用其 GetValue() 方法:)

PropertyInfo inf = typeof(YourClass).GetProperty("PropertyName");
MyList.Where(x => inf.GetValue(x) == "MyName");

为了让它工作,变量Name当然应该是一个Property,如下所示:

public string Name { get; set; } 

希望有帮助:)

关于c# - .Where 语句中的 LINQ 动态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941471/

相关文章:

c# - 在单个测试类中测试接口(interface)的多个实现

c# - 在左侧方向更改 c# 表单应用程序宽度

c# - 如何在命令启动后更改 sql 超时

c# - 具有C#DirectoryEntry类的多个LDAP连接器

C# 2 DateTime 不相等

c# - 如何检查 Canvas 矩形内的 UI 矩形

c# - 为什么 cpu 性能计数器一直报告 0% cpu 使用率?

c# - 在其他类中组合一个类的对象时如何进行验证?

c# - 单链表队列在一定大小时抛出SO异常

c# - 为 Tablet PC 开发时,如何确定用户点击的是鼠标还是笔?