C# 使用 Linq 执行包含多个值的操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15235661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:34:08  来源:igfitidea点击:

Using Linq to do a Contains with multiple values

c#linqcontains

提问by Jhorra

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.

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

EDIT 2Here is the error I recieve.

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

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

采纳答案by sa_ddam213

Maybe somthing like

也许像

C# Linq:

C# 林克:

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

回答by aush

If I've understood your right:

如果我理解你的权利:

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

回答by Umar Farooq Khawaja

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;

回答by chead23

I think you want to try:

我想你想尝试:

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

回答by Linkanyway

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