2

trying to learn Linq but bumping against a wall here.

Im trying to find all articles that contain multiple strings, but not sure how to use the .Contains when passing in a List.

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();
}

what wold be the correct syntax here?

Darkmage
  • 1,583
  • 9
  • 24
  • 42
  • 1
    When you say "articles that contain multiple strings", do you mean all of the strings? Or just more than one? – Alex Apr 25 '13 at 12:09
  • 1
    possible duplicate of [To check if a string contains an element from a list (of strings) - Is there a better way to write this code?](http://stackoverflow.com/questions/500925/to-check-if-a-string-contains-an-element-from-a-list-of-strings-is-there-a-b) – NominSim Apr 25 '13 at 12:10
  • I need all strings to match. – Darkmage Apr 25 '13 at 12:21

3 Answers3

5

[Edit] Supposing that BodyText is of type string

you can try this:

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

or

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

[Edit 2] replacing str => art.BodyText.Contains(str) by art.BodyText.Contains

polkduran
  • 2,533
  • 24
  • 34
  • This will work although it will be inefficiently iterating over the body text multiple times – Alex Apr 25 '13 at 12:10
  • 1
    Note that you can replace `str => art.BodyText.Contains(str)` with just `art.BodyText.Contains` – Robert J. Apr 25 '13 at 12:13
  • @AlexG : I don't think there is another alternative than iterating through both 'search items' and 'body text', it's like a 'join' – polkduran Apr 25 '13 at 12:17
2

With LINQ

var artList= (from art in artFullList
              from search in searchStrs 
              where art.Bodytext.Contains(search)
              select art).ToList();
Jurica Smircic
  • 6,117
  • 2
  • 22
  • 27
1
var artList = artListfull.Where(a => searchStrs.Any(s => a.Bodytext.Contains(s)))
                         .ToList();
I4V
  • 34,891
  • 6
  • 67
  • 79