Using LINQ to Entities, how can I determine if any item from a List of ints exists in a comma delimited string of ints?
For example, I want to write something like the following (logically):
collection.Where(collection.DelimitedStringOfInts.Contains(listOfInts.AnyOfThem))
Also, I should mention that I'm doing this using LINQ method chaining, with the delimited string as part of the entity -
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 Alex's referenced article, I implemented a working solution as follows:
var query = from x in Db.Items select x;
var listOfInts = GetListOfInts();
if (listOfInts != null && listOfInts.Any())
{
//"ToListOfStrings" is a simple extension method I wrote to create a List<string> from a List<int>
var delimitedIds = listOfInts.ToListOfStrings(',');
query = query.Where(
BuildOrExpression<DatabaseItem, string>(x => x.DelimitedStringOfInts, delimitedIds)
);
}
An update was required to the "BuildOrExpression" referenced in the article. The "equals" operator had to be changed to a "contains" operator.
var contains = values.Select(value =>
(Expression)Expression.Call(
valueSelector.Body,
typeof(string).GetMethod("Contains"),
Expression.Constant(
value,
typeof(TValue)
)
)
);