2016-11-27 119 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