查找包含linq单词的所有文章

时间:2013-04-25 12:01:36

标签: c# asp.net linq

试图学习Linq,但在这里撞墙。

我试图找到包含多个字符串的所有文章,但不确定如何在传入List时使用.Contains。

private void SearchArticles()
{
    AdminEntities db = new AdminEntities();

    var searchStrs = new List<string> {"search_string1", "search_string2"};
    var artListfull = db.view_M02Articles_SearchPublished(0, "").ToList();
    var artList = artListfull.FindAll(n => n.Bodytext.Contains(searchStrs));

    Label1.Text = artList.Count.ToString();
    Repeater1.DataSource = artList;
    Repeater1.DataBind();
}

这里的正确语法是什么?

3 个答案:

答案 0 :(得分:5)

[编辑] 假设BodyText的类型为string

你可以试试这个:

//the article body must contain "ALL" the search terms
var artList = artListfull.Where(art => searchStrs.All(art.BodyText.Contains));

//the article body must contain "At least one" of the search terms
var artList = artListfull.Where(art => searchStrs.Any(art.BodyText.Contains));

[编辑2] str => art.BodyText.Contains(str)替换为art.BodyText.Contains

答案 1 :(得分:2)

使用LINQ

var artList= (from art in artFullList
              from search in searchStrs 
              where art.Bodytext.Contains(search)
              select art).ToList();

答案 2 :(得分:1)

var artList = artListfull.Where(a => searchStrs.Any(s => a.Bodytext.Contains(s)))
                         .ToList();