How do I do a Contains() in DLINQ with a list of items?

c# dynamic-linq

Question

I want to build a dlinq query that checks to see if a title has any number of items in it. I know you can do .Contains() with a list, but I need to check if the title contains any of the items, not if the items contain part of the title. For example: I have three items in the list "bacon, chicken, pork". I need the title of "chicken house" to match.

   var results = (from l in db.Sites
   where list.Contains(l.site_title)
   select l.ToBusiness(l.SiteReviews)).ToList();

If I try the first 2 answers, I get an error "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."

The third solution gives me

Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL."

1
1
7/10/2012 3:10:21 PM

Accepted Answer

I finally figured it out. Thanks to my good buddy Cory for the help. There are two ways you can do it.

var resultSets = (from k in list
                  select (from b in db.Sites
                          where b.site_title.Contains(k)
                          select b.ToBusiness()).ToList<Business>()).ToList();

 List<Business> all = new List<Business>();

 for (int i = 0; i < resultSets.Count; ++i)
 {
     all.AddRange(resultSets[i]);
 }

This is a linq query that will successfuly do what is stated. As well, you can also just build the sql query in plain text by hand.

1
3/4/2009 4:54:03 AM

Popular Answer

Try the following. You can use a combination of Where and Any to search for substring matches.

var results = (from l in db.Sites
                where list.Where(x => 0 != x.IndexOf(l)).Any()
                select l.ToBusiness(l.SiteReviews)).ToList();


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow