Using Linq to do a Contains with multiple values

103,187

Solution 1

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();

Solution 2

I think you want to try:

var query = Medications.Where(m => names.Contains(m.BrandName) || names.Contains(m.GenericName));

Solution 3

If I've understood your right:

var meds = Medications.Where(m => names.Contains(m.BrandName) || names.Contains(m.GenericName));

Solution 4

Just do a join between the medication table and the names array.

var query = from m in Medications
            from n in in names
            where m.BrandNames.Any(bn => bn.Contains(n)) || m.GenericNames.Any(gn => gn.Contains(n))
            select m;
Share:
103,187
Suspe18
Author by

Suspe18

Updated on July 05, 2022

Comments

  • Suspe18
    Suspe18 almost 2 years

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