Reputation: 191
I am facing a problem regarding a LINQ query.
I have multiple input values which is stored in List< string > variable.
I have to form a LINQ query which would have a where clause which check for the respective column with CONTAINS keyword. The issue I am facing is that List< string > can contain any number of values in it.
So i want to know how can i form a query which can read input values from collection object. and display the result.
Any suggestion would be appreciated.
Thanks in advance.
Upvotes: 0
Views: 7025
Reputation: 13049
Linq extension method:
public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)
{
return Collection.Any(x=> Values.Contains(x));
}
Then you can use like:
List<string> List1 = getStringList1();
List<string> List2 = getStringList2();
bool List2ItemsInList1 = List1.ContainsAny(List2);
Upvotes: 2
Reputation: 16067
Your question is not clear. Suppose you have three values X, Y and Z. If you want to fetch the results where a Column is either X, Y or Z, then habib-osu's answer will do this.
If you are looking for all records where a particular column contains X, Y and Z then the following should work
List<string> options = new List<string>();
options.Add("X");
options.Add("Y");
options.Add("Z");
var query = (from r in dc.Table select r);
foreach(var option in options)
query = (from r in query where r.Column.Contains(option) select r);
var list = query.ToList();
This will produce one sql query similar to the following
select * from Table where Column like '%X%' and column like '%Y%' and column like '%Z%'
Upvotes: 0