使用Linq执行包含多个值的包含

时间:2013-03-05 22:48:20

标签: c# linq contains

我有一张药物表,我正在寻找某些药物名称,但我需要搜索多个名字。这是我目前所处的位置。

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

我所拥有的不起作用,而且我现在卡住了。我知道我很接近,但我无法弄清楚出了什么问题。

修改

为了澄清,如果我要搜索的名称是desirudin,那么BrandName或Generic名称会更长,所以我必须在数据库中的字段上包含。

编辑2 这是我收到的错误。

Unsupported overload used for query operator 'Any'.

这是我最终的结果

var meds = (from m in db.AdmissionMedications where 
(names.Any(n => m.BrandName.Contains(n)) || names.Any(n => m.GenericName.Contains(n))
) select m);

5 个答案:

答案 0 :(得分:23)

也许像是

C#Linq:

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

扩展方法:

List<Medication> meds = Medications
    .Where( med =>
        names.Any( name =>
            name.Equals( med.BrandName ) || med.GenericName.Contains( name )
        )
    )
    .ToList();

答案 1 :(得分:2)

我想你想尝试一下:

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

答案 2 :(得分:1)

只需在药物表和名称数组之间进行连接。

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;

答案 3 :(得分:0)

如果我理解你的权利:

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

答案 4 :(得分:0)

var x = (from c in Reports where c.HKPlanningQty == xi select c).Select(u=>new {Style=u.Style,QTN=u.HKPlanningQty}).OrderBy(u =>u.Style ).Where(v=>v.Style.Contains("44")||v.Style.Contains("58"));