C# 整数包含使用 Linq

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17110850/
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 08:37:54  来源:igfitidea点击:

Integer Contains Using Linq

c#entity-frameworklinqcasting

提问by Andrew

I'm having some difficulty writing a linq query that will check whether the consecutive digits in an integer are contained in the primary key of a table. So, suppose there is a table called Employeeswith a primary key on the column Employees.Id. Suppose this primary key is of Sql Server datatype INT. I would like to write a linq query using Entity Framework Code First that will return all employees whose primary key contains the string 456. Something like:

我在编写 linq 查询时遇到了一些困难,该查询将检查整数中的连续数字是否包含在表的主键中。所以,假设有一个表Employees,在列上有一个主键Employees.Id。假设这个主键是 Sql Server 数据类型INT。我想使用 Entity Framework Code First 编写一个 linq 查询,该查询将返回主键包含字符串 456 的所有员工。类似于:

string filter = "456";

var results = from e in myDbContext.Employees
  where e.Id.Contains(filter)
  select e;

The problem is that the Contains method is not offered for integer datatypes in C#...

问题是 C# 中的整数数据类型不提供包含方法...

采纳答案by xlecoustillier

Try:

尝试:

var results = from e in myDbContext.Employees
  where SqlFunctions.StringConvert((double)e.Id).Contains(filter)
  select e;

回答by Arif Anwarul

You can convert both to string and then do the query. In your case:

您可以将两者都转换为字符串,然后进行查询。在你的情况下:

string filter = "456"; var results = from e in myDbContext.Employees where e.Id.ToString().Contains(filter) select e;

string filter = "456"; var results = from e in myDbContext.Employees where e.Id.ToString().Contains(filter) select e;