2016-11-27 120 views
0

我有一個問題在另一個列表中過濾列表屬性。 我正在嘗試使用Linq。如何過濾另一個列表中的列表MVC LINQ

我有一個文件列表,他們每個人都有一個作者列表。 我有一個searchString參數,我從視圖中得到我想讓作者的姓氏平等。我能夠用類文檔的其他屬性來完成它,但我無法在列表中執行此操作。

這是我的代碼:

public ActionResult Index(string searchBy,string searchString) 
{ 
    db.Documentos.Include(l => l.Pais); 
    db.Documentos.Include(l => l.Etiquetas); 
    db.Documentos.Include(l => l.Autores); 
    var documentos = from m in db.Documentos select m; 
    if (searchBy=="Titulo"&& !string.IsNullOrEmpty(searchString)) 
    { 
     documentos = documentos.Where(s => s.Titulo.Contains(searchString)); 
    } 
    if(searchBy =="Fecha" && !string.IsNullOrEmpty(searchString)) 
    {     
     documentos = documentos.Where(s => s.Fecha.ToString().Contains(searchString)); 
    } 
    if(searchBy == "Autor" && !string.IsNullOrEmpty(searchString)) 
    { 
     documentos = documentos.Where(x => documentos.All(y => y.Autores.All(a => a.Apellido.Contains(searchString)))); 

    // this doesn't return anything, I cant filter with this. 
    } 
    return View(documentos.ToList()); 
} 

回答

0

您應該使用Any方法。

documentos = documentos.Where(d => d.Authors.Any(f => f.LastName == searchString)); 

這將爲您提供任何作者姓氏等於搜索字符串的文檔列表。如果您沒有查找姓氏的確切值,而是查找子字符串,則可以使用Contains方法。

documentos = documentos.Where(d => d.Authors 
            .Any(f => f.LastName.Contains(searchString))); 
+1

謝謝!有效!! – EmiL

+1

@EmiL如果它有效,你可能想標記接受的答案,這樣可以幫助其他人。這裏有更多的信息,爲什麼接受答案是好的:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – CodingYoshi

+0

我不知道,謝謝你的信息:) – EmiL