开发者

C# Linq where clause .Contains(string[])

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.


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 [...]


try using a regex and the .Any method:

where  (from yy in BodyTypes  
        select yy).Any( y => (new Regex(v.Header36.ToString())).IsMatch(y))


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)) ) 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜