简体   繁体   English

使用 IN 运算符并在 LINQ C# 中获取不同的值

[英]Use IN operator and get distinct values in LINQ C#

I have the below SQL query, Which I need to convert to LINQ.我有以下 SQL 查询,我需要将其转换为 LINQ。 The SQL query: SQL 查询:

select distinct a.DeliverableAdditionalFieldId, b.FieldName, b.CustomFieldType
from PrefixDeliverableAdditionalFieldsMapping as a, DeliverableAdditionalField as b
where a.DeliverableAdditionalFieldId = b.Id
and b.IsActive = 1
and a.PrefixId in (184,183)

I converted the sql query to LINQ which is below:我将 sql 查询转换为 LINQ 如下:

var prefixIds = "184, 183"

from prefix in context.PrefixDeliverableAdditionalFieldsMappings
join additionalField in context.DeliverableAdditionalFields on prefix.DeliverableAdditionalFieldId equals additionalField.Id
where additionalField.IsActive == true && prefixIds.Contains(prefix.PrefixId.ToString())
select new AdditionalCustomField
{
    AdditionalFieldId = prefix.DeliverableAdditionalFieldId,
    AdditionalFieldName = additionalField.FieldName,
    FieldType = additionalField.CustomFieldType

}).Distinct().ToList()

For IN Operator of SQL, in LINQ I used the code: prefixIds.Contains(prefix.PrefixId.ToString(). Now I need to sure that this is OK. Please let me know is there any other alternative way?对于 SQL 的 IN 运算符,在 LINQ 中我使用了代码:prefixIds.Contains(prefix.PrefixId.ToString()。现在我需要确定这没问题。请让我知道还有其他替代方法吗?

And is there any alternate way to use distinct and the way I used, will it work?有没有其他方法可以使用 distinct 和我使用的方式,它会起作用吗?

You are now doing .Contains() on a string, so eg "1" will also be found, and I'm pretty sure you don't want that to happen.您现在正在对字符串执行.Contains() ,因此也会找到例如“1”,我很确定您不希望这种情况发生。

Instead, define prefixIds as a collection of the desired type, eg int[] :相反,将prefixIds定义为所需类型的集合,例如int[]

var prefixIds = new[] { 184, 183 };

And then you can use it as follows:然后您可以按如下方式使用它:

where ..... && prefixIds.Contains(prefix.PrefixId)

This translates to a SQL IN (...) clause.这转换为 SQL IN (...)子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM