【问题标题】:Using Contains in LINQ for "IN" clause - different between strings and bytes在 LINQ 中为“IN”子句使用包含 - 字符串和字节之间不同
【发布时间】:2015-12-16 21:47:02
【问题描述】:

我正在尝试创建一个 LINQ 查询来提取特定的子类型,这些子类型在表中存储为字节。我尝试了几种变体,并让它强制进出字符串;但我无法使用数字版本。我认为这是我无法正确理解的某种 c# 规则,但我不确定在哪里看。有什么建议吗?

// This works okay, but doesn't makes sense to go in/out of string

string[] subTypes = { "2", "4" };      //  2 = Clinic, 4 = SubClinic
var clinics = from o in db.Locations
         where subTypes.Contains(o.LocationType.ToString())
        select o.Name;

// this version shows an error on the "where" clause
// byte[] does not contain a definition for 'Contains'...

byte[] subType = { 2, 4 };      //  2 = Clinic, 4 = SubClinic
var clinic = from o in db.Locations
        where subType.Contains(o.LocationType) 
       select  o.Name;

【问题讨论】:

  • 定义“无法 [it] 工作”
  • 属性o.LocationType的类型是什么?
  • 我的 EF 有点生疏了,where subType.Any(x=> x == o.LocationType) 有用吗?
  • Entity Framework 用 byte[] 做了一些有趣的事情:lehmamic.wordpress.com/2012/08/14/…
  • o.LocationType 被定义为 tinyint,我假设它与 byte 相同;他们不是所以我需要说 subType.Contains(byte)o.LocationType)

标签: c# linq contains


【解决方案1】:

所以当我尝试时:

byte[] subType = { 2, 4 };
var locationType = 2;
Console.WriteLine(subType.Contains(locationType));
Console.ReadLine();

我遇到了和你一样的错误。将代码更改为:

byte[] subType = { 2, 4 };
var locationType = (byte)2;
Console.WriteLine(subType.Contains(locationType));
Console.ReadLine();

效果很好。 LocationType 是否可能不是字节而是 int?

【讨论】:

  • “无法正常工作”是指编译器显示有关 Contains 的错误。我猜想 SQL 类型的 tinyint 和 c# 类型的 byte 不是 100% 兼容的,所以需要强制转换。 byte[] subType = { 2, 4 }; // 2 = Clinic, 4 = SubClinic ` var Clinic = from db.Locations 中的 ` ` where subType.Contains((byte)o.LocationType)` ` select o.Name;`
【解决方案2】:

因为您使用的是 var 关键字,所以您的 locationType 变量的定义类似于 int。

var locationType = 2;
// Equivalent to
int locationType = 2;

当有任何歧义时,使用显式类型声明:

byte locationType = 2;

【讨论】:

  • 感谢您的回答,但我没有将 locationType 声明为 var。 locationType 是 SQL DB 表中的一个属性,定义为 tinyint。我认为 tinyint 和 byte 是相同的,所以我没有想到我需要强制 tinyint 转换为字节。您的回答是正确的,而且很有帮助,除了需要在 c# 代码中进行显式输入之外,对于数据库的构建方式无能为力。
  • 如果您确实存储了一个字节,您可以更改 SQL Server 中列的类型或将结果转换为 SQL
猜你喜欢
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多