Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to do a Contains with multiple values

Tags:

c#

contains

linq

I have a medication table that I'm looking for certain drug names, but I need to search for multiple names. Here is where I currently am with it.

string[] names = new string[2];
names[0] = "apixaban";
names[1] = "desirudin";

var meds = (from m in Medications where names.Any(m.BrandName.Contains) || names.Any(m.GenericName.Contains) select m);

What I have isn't working, and I'm currently stuck. I know I'm close, but I can't quite figure out what's wrong.

EDIT

For clarification, if the name I'm searching for is desirudin, then the BrandName or Generic name will be longer, so I have to have the contains on the field in the database.

EDIT 2 Here is the error I recieve.

Unsupported overload used for query operator 'Any'.

Here is what I finally ended up with

var meds = (from m in db.AdmissionMedications where 
(names.Any(n => m.BrandName.Contains(n)) || names.Any(n => m.GenericName.Contains(n))
) select m);
like image 377
Jhorra Avatar asked Mar 05 '13 22:03

Jhorra


People also ask

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.


2 Answers

Maybe somthing like

C# Linq:

var meds = (from m in Medications 
            where names.Any(name => name.Equals(m.BrandName) || m.GenericName.Contains(name)) 
            select m);

Extension methods:

List<Medication> meds = Medications
    .Where( med =>
        names.Any( name =>
            name.Equals( med.BrandName ) || med.GenericName.Contains( name )
        )
    )
    .ToList();
like image 144
sa_ddam213 Avatar answered Sep 28 '22 07:09

sa_ddam213


I think you want to try:

var query = Medications.Where(m => names.Contains(m.BrandName) || names.Contains(m.GenericName));
like image 23
chead23 Avatar answered Sep 28 '22 06:09

chead23