2017-03-02 36 views
-1
public Class SomeModel 
{ 
    public int Id { get; set;} 

    public string Name {get; set;} 
} 

查詢這是我結合值上述模型的方法,它包含了內聯SQL使用上面的方法,我想過濾,包含ID的所有記錄查詢凡在LINQ

Public ActionResult GetData() 
{ 
    IEnumarable<SomeModel> alltheListValues = .... 
} 

在下面的字符串。

string filterIds = "12,13,14,15"

SomeModel模型類Id值是整型,但我有字符串類型ID設置,而不去爲這個循環,我決定使用其中的查詢過濾此。

,因爲其中的查詢,我們可以Linq中獲得儘可能contains

我寫下follwoing功能來篩選值

IEnumarable<SomeModel> filterValues = GetData.Where(Id=> Id.ToString().Contains(filterIds)); 

但這不選擇任何值始終爲零過濾結果,我該怎麼寫這正確

+0

那是LINQ查詢什麼你在用嗎?因爲它甚至不會編譯。 –

+1

GetData返回ActionResult。你如何能夠運行Where方法? –

回答

1

這可能是很長的路要走:

string filterIds = "12,13,14,15"; 

//Convert filterIds string into a integers collection 
var ids=filterIds.Split(',').Select(int.Parse); 

IEnumarable<SomeModel> filterValues = GetData().Where(sm=> ids.Contains(sm.Id)); 

有一件事我現在注意到的是你的GetData方法的簽名,我覺得你的意思是:

public IEnumarable<SomeModel> GetData() 
{ 
    IEnumarable<SomeModel> alltheListValues = .... 
    //... 
    return alltheListValues; 
} 
0

有一個數組/集合,而不是一個列表,並檢查ID是否在它。

IEnumarable<SomeModel> filterValues = ActualGetData().Where(n => filterIds.Contains(n.Id)) 

Where ActualGetData()返回給你一個IEnumarable。
在當前的代碼的GetData()返回一個ActionResult作爲德魯·肯尼迪提到

+0

有兩件事是錯誤的,它更多的是與這個問題有關。 1)GetData是一個函數,所以它需要括號。 2)它返回ActionResult,所以這不會編譯。 –

+0

啊是的!感謝您指出了....我已更新代碼 –

0

如果你確信「ID」的集合中的所有元素將轉換爲數字,那麼你可以用下面的辦法。

var models = new List<SomeModel>(); //Consider that this collection is coming from some service or repository. 
var Ids = filterIds.Split(',').Select(x => int.Parse(x)); 
IEnumarable<SomeModel> filterValues = models.Where(n => Ids.Contains(n.Id)); 

您的代碼無法編譯,所以我只是在這裏發佈邏輯代碼​​。您可以根據您的要求使用它。

+0

實際上這個字符串整數轉換是錯誤的那裏得到一個異常,無論如何感謝您的支持! – kez