Using LINQ to Entities, how can I determine if there is any element from an int list in a comma-delimited string?
For example, I want to write something like the following (logically):
collection.Where(collection.DelimitedStringOfInts.Contains(listOfInts.AnyOfThem))
Also, I should mention that I am doing this using the LINQ method chain, with a separator string as part of the object -
var listOfInts = GetListOfInts();
var query = from x in Db.Items select x;
if (listOfInts != null && listOfInts.Count() > 0)
{
query = query.Where(x => x.DelimitedStringOfInts.Contains(listOfInts.AnyOfThem));
}
UPDATE:
Using an article linking to Alex, I implemented a working solution as follows:
var query = from x in Db.Items select x;
var listOfInts = GetListOfInts();
if (listOfInts != null && listOfInts.Any())
{
var delimitedIds = listOfInts.ToListOfStrings(',');
query = query.Where(
BuildOrExpression<DatabaseItem, string>(x => x.DelimitedStringOfInts, delimitedIds)
);
}
The BuildOrExpression referred to in the article requires an update. The equal operator should have been replaced by the contains operator.
var contains = values.Select(value =>
(Expression)Expression.Call(
valueSelector.Body,
typeof(string).GetMethod("Contains"),
Expression.Constant(
value,
typeof(TValue)
)
)
);
source
share