如何在 LINQ 查询中使用 PropertyName

   2024-10-07 8510
核心提示:在 LINQ 查询中使用 PropertyName,可以通过使用反射来动态获取属性名称,然后在查询中使用该属性名称。以下是一个示例:假设有

在 LINQ 查询中使用 PropertyName,可以通过使用反射来动态获取属性名称,然后在查询中使用该属性名称。以下是一个示例:

假设有一个名为 Person 的类,其中有一个属性为 Name:

public class Person{    public string Name { get; set; }}

现在假设有一个 List<Person> 类型的集合,我们想要查询这个集合中所有 Name 属性为 “John” 的对象。可以通过以下方式使用 PropertyName:

List<Person> persons = new List<Person>{    new Person { Name = "John" },    new Person { Name = "Mary" },    new Person { Name = "John" }};string propertyName = "Name";string propertyValue = "John";var results = persons.Where(p => p.GetType().GetProperty(propertyName).GetValue(p).ToString() == propertyValue);foreach (var person in results){    Console.WriteLine(person.Name);}

在上面的示例中,我们首先定义了要查询的属性名称和属性值。然后在 LINQ 查询中使用 GetType().GetProperty(propertyName).GetValue(p) 来获取属性值,并将其与指定的属性值进行比较。最后,我们将查询结果打印出来。

请注意,使用反射来获取属性值可能会降低性能,因此应慎重使用。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号