开发者

Dynamic linq-to-sql that queries based on multiple keywords

I had been putting together a simple little search.

IEnumerable<Member> searchResults = (from m in members
                                     where m.ScreenName.ToUpper().Contains(upperKeyword)
                                     select m).AsEnumerable();

An then I realized this if the user typed in "keyword1 keyword2", this little query will always search for that exact string. So, 开发者_如何学运维I decided I should probably split keywords

string[] keywords = upperKeyword.split(' ');

and then I ran into an issue. I can't really do this:

IEnumerable<Member> searchResults = (from m in members
                                     where m.ScreenName.ToUpper().Contains(keywords) // array of string
                                     select m).AsEnumerable();

because .Contains() doesn't take array. How could I accomplish this?


Try this (untested):

IEnumerable<Member> searchResults = members.ToList().Where(m => keywords.Any(k => m.Summary.Contains(k)))

Edit

Added .ToList(), as I don't think LINQ will be able to convert the above into SQL, so we'll have to perform this in-memory.


For Exact Matches:

Try the inverse of what you have: where keywords.Contains(m.ScreenName)

For reference, Creating IN queries with LINQ-to-SQL

For Partial Matches:

string[] keywords = new[]{ ... };
var results = db.members.Where(m => keywords.Any(sn => m.ScreenName.Contains(sn)));

No compilation error here, but I don't have the data to test against.


I think you need to convert the array to a list. I'm just on my way out of the office, but I think this should work.

IEnumerable<Member> searchResults = (from m in members
                                     where keywords.ToList().Contains(m.ScreenName.ToUpper()) // array of string
                                     select m).AsEnumerable();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜