在与属性集值相等的类属性值列表中搜索

本文关键字:属性 列表 搜索 | 更新日期: 2023-09-27 18:07:58

我尝试获得一个新的myClass列表,其中它们的属性等于一个虚拟类属性集。我不知道该怎么写linq表达式。特别是列表来自EntityFramework,所以如果没有必要,我不想一次拉出所有的数据。

:

public class MyClass
    {
        public int MyInt { get; set; }
        public string MyString { get; set; }
        public bool MyBool { get; set; }
        public DateTime MyDate { get; set; }
    }
    public List<MyClass> myClassList = new List<MyClass>();
    /// <summary>
    /// 
    /// </summary>
    /// <param name="myClass">A Dummy Class where stored the searched values</param>
    /// <param name="searchingPropertiesName">a string array where stored the searched property names</param>
    public void MySearch(MyClass myClass, string[] searchingPropertiesName)
    {
        var propInfo = new List<System.Reflection.PropertyInfo>();
        foreach (System.Reflection.PropertyInfo myClassProp in typeof(MyClass).GetProperties(System.Reflection.BindingFlags.Public))
        {
            foreach (string searchPropName in searchingPropertiesName)
            {
                if (myClassProp.Name != searchPropName)
                {
                    return;
                }
                propInfo.Add(typeof(EventSeries).GetProperty(searchPropName));
            }
        }

        var searchedList = myClassList.Where(e => e... "e.Property values are equal propInfo.values");
    }

谢谢!

在与属性集值相等的类属性值列表中搜索

我在下面写的这个版本只会真正正确地工作与链接到对象。虽然这是一个有趣的学术问题,但您不应该在生产中使用这种方法。您使用原型值和已命名的属性列表的动态谓词的想法不会转化为Linq-to-Entities(它不会生成好的SQL)。我建议你动态地构建一个查询(使用IQueryable.Where,并寻找LinqKit)。

private static readonly Dictionary<String,PropertyInfo> _properties = typeof(MyClass).GetProperties().ToDictionary( pi => pi.Name );
public IEnumerable<MyClass>Search(MyClass prototype, IEnumerable<String> propertiesToFilter, IEnumerable<MyClass> items) {
    IEnumerable<PropertyInfo> selectedProperties = propertiesToFilter
        .Select( name => _properties[ name ] )
        .ToList();
    return items
        .Where( i => selectedProperties
            .Select( pi => pi.GetValue( i )
            .SequenceEquals( _selectedProperties
                .Select( pi => pi.GetValue( prototype ) )
        );
}