2016-07-15 67 views
1

類的具有對象列表的列表過濾由字符串屬性的

public class AlldataPoints 
    { 
    public int phase{ get; set; } 
    public string recr{ get; set; } 
    public string study{ get; set; } 
    } 


public class filter 
{ 
    public List<string> Phase; 
    public List<string> recr; 
    public List<string> study; 

} 

我具有高於類的列表說Alldatapoints「LST」和類濾波器的對象OBJ'。

我想只過濾那些'obj'階段的值與'lst''phase'匹配的'lst'行,'obj'中的'recr'的值匹配'lst'中的'recr' ''recr'。我想使用實體表達式。

filter obj; 
IEnumerable<AlldataPoints> lst; 
var result = lst.Where(item => obj.Phase.Contains(item.phase) && obj.recr.Contains(item.recr)); 
+0

您已經標記與實體框架。這是一個實際的'名單'或在你的DbContext設置一個實體「Alldatapoints名單」?這可能會影響可能的答案。如果它是一個實際列表,則刪除entity-framework標籤。 – Rhumborl

回答

1

的過濾器參數列表中使用Contains

public List<AlldataPoints> FilterPoinst(List<AlldataPoints> points, filter filter) 
{ 
    return points.Where(x => filter.Phase.Contains(x.phase) 
     && filter.recr.Contains(x.recr) 
     && filter.study.Contains(x.study)).ToList(); 
} 

如果您需要匹配ONY一個屬性,則只是||運營商更換&&

在你的代碼只是調用這個函數:

var filter = new filter(); //init your filter 
List<AlldataPoints> points = new List<AlldataPoints>(); // Here you should get your points 
var filteredPoints = FilterPoinst(points, yourFilter); //you get your filtered points. 
0

在這裏你去:

0

如果這是針對您的DbContext的Linq-to-Entities查詢,則仍然可以使用Contains()來檢查每個值是否在每個對應的列表中。

一旦尷尬的事情是,你需要phase轉換爲字符串,因爲它是一個int和列表是List<string>,但你不能只用ToString(),你必須使用SqlFunctions.StringConvert() - 見this answer

dbContext.AllDataPoints.Where(adp => 
    filter.Phase.Contains(SqlFunctions.StringConvert((double)adp.phase).Trim()) 
    && filter.recr.Contains(adp.recr) 
    // && filter.study.Contains(adp.study) 
)