首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何按属性名称筛选类列表?

如何按属性名称筛选类列表?
EN

Stack Overflow用户
提问于 2017-05-18 07:38:23
回答 1查看 1.9K关注 0票数 1

我想以字符串的形式通过属性名筛选类的集合。假设我有一个名为Person的类,我有一个它的集合,或者是IEnumerable,或者是List,我想过滤这个集合,但是我不知道确切的过滤器,我的意思是我不能使用:

代码语言:javascript
复制
person.Where(x => x.Id == 1);

让我举一个例子。

代码语言:javascript
复制
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int YearOfBorn {get; set;}    
}

现在,我创建了一个集合,比如:

代码语言:javascript
复制
List<Person> p = new List<Person>();

现在,我想过滤所有名为Alex的人,但是我想使用以下函数过滤它:

代码语言:javascript
复制
public List<Person> Filter(string propertyName, string filterValue, List<Person> persons)

那么,如果我想使用Linq或Lambda,我如何过滤它呢?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-18 07:49:16

从技术上讲,您可以尝试使用反射

代码语言:javascript
复制
using System.Reflection;

... 

// T, IEnumerable<T> - let's generalize it a bit
public List<T> Filter<T>(string propertyName, string filterValue, IEnumerable<T> persons) {
  if (null == persons)
    throw new ArgumentNullException("persons");
  else if (null == propertyName)
    throw new ArgumentNullException("propertyName");

  PropertyInfo info = typeof(T).GetProperty(propertyName);

  if (null == info)
    throw new ArgumentException($"Property {propertyName} hasn't been found.", 
                                 "propertyName");

  // A bit complex, but in general case we have to think of
  //   1. GetValue can be expensive, that's why we ensure it calls just once
  //   2. GetValue as well as filterValue can be null
  return persons
    .Select(item => new {
      value = item,
      prop = info.GetValue(item),
    })
    .Where(item => null == filterValue
       ? item.prop == null
       : item.prop != null && string.Equals(filterValue, item.prop.ToString()))
    .Select(item => item.value)
    .ToList();
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44041476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档