Reputation: 127
Ive been googling for the last few hours to find a solution to my problem but im stumpped. I was wondering if someone could help me out with the following.
I have a Linq query that queries against a DataTable. I have a param of string[] BodyTypes that holds strings like "5,7,11" or "6,7,4" or just "5,"
the Linq i have is:
var query2 = (from v in query.AsEnumerable()
where (from yy in BodyTypes
select yy).Contains(v.Header36.ToString())
select new
{
PartNumber = v.PartNumber,
Position = v.Position,
ImagePath = v.ImagePath,
Supplier = v.Supplier,
Price = v.Price,
RRP = v.RRP,
Stock = v.Stock,
BaseCat = v.BaseCat,
Description = v.Description,
Header36 = v.Header36,
GT_Id = v.GT_Id
});
v.Header36 has different values assigned to it per row i.e. "11,7,4,5" or "11,6,7"
My problem is how do i make a match using Linq, i want to match Header36 with anything that is passed in the string[]BodyTypes array like using a wild card or like statement. My problem is also this DataTable is loaded from a 3rd party's webservice, so no SQL backend can be used here. Any suggestions would be greatfully appreciated.
Kind Regards Neil.
Upvotes: 0
Views: 3979
Reputation: 1500335
Making it LINQ to Objects actually means it's easier to answer. I think you want something like:
from v in query.AsEnumerable()
let headers = v.Header36.Split(',')
where yy.BodyTypes.Intersect(headers).Any()
select new [...]
Note that your (from yy in BodyTypes select yy)
is mostly equivalent to just BodyTypes
(at least it will be given the way you're then using it) - you don't need to use a query expression every time you want to do anything.
Here's a slightly more efficient version:
HashSet<String> bodyTypes = new HashSet<String>(yy.BodyTypes);
var query = from v in query.AsEnumerable()
let headers = v.Header36.Split(',')
where bodyTypes.Overlaps(headers)
select new [...]
Upvotes: 1
Reputation: 16018
If i have understood this correct your body time might contain 1,2,3,4
and your Header36 might contain 2,5
and you want to match when an item appears in both delimted strings ?
Change your where clause
where (from yy in BodyTypes select yy)
.Any(bts=> bts.Split(',').Any(bt=> v.Header36.Split(',').Contains(bt)) )
Upvotes: 0
Reputation: 3100
try using a regex and the .Any method:
where (from yy in BodyTypes
select yy).Any( y => (new Regex(v.Header36.ToString())).IsMatch(y))
Upvotes: 0