2016-09-21 123 views
0

我尝试获取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"); 
    } 

谢谢!

+0

你想比较一个特定的属性,或所有的? –

回答

0

我在下面写的这个版本只能真正适用于Linq-to-Objects。虽然一个有趣的学术问题,你不应该在生产中使用这种方法。您对使用原型值和属性名称列表的动态谓词的想法不会转化为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)) 
     ); 
} 
+0

谢谢你的时间,并回答这是一个很好的解决方案。 我想多一点,是的,我不想在生产中使用它,所以寻找替代解决方案,我决定使用“通用存储库模式”,并使用“automapper”。 – Neuronetic