gpt4 book ai didi

sql - 数字匹配的 LINQ 查询

转载 作者:行者123 更新时间:2023-12-04 21:06:57 30 4
gpt4 key购买 nike

我有一个名为 dbo.Question 的表,其中包含两列 IdTitle。我想编写 LINQ 查询以获取所有问题标题以数字开头 的问题。

以下是“标题”以数字开头的问题搜索结果示例:

  • 5 个有用的 Visual Studio 快捷方式
  • 关于 Hadoop 的 7 件事。
  • 您应该感谢黑客的 10 个理由

SQL 查询是这样的:

SELECT Title FROM dbo.Question WHERE Title NOT LIKE '[a-z]%'

上述 SQL 查询的 LINQ 等价物是什么?

最佳答案

var query = from x in dbcontext.Questions
where SqlFunctions.IsNumeric(EntityFunctions.Left(x.Title, 1)) == 1
select x;

来源:

http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.isnumeric(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/dd383069(v=vs.110).aspx

想想看,这不是很有效,因为它不使用索引。你可以改为这样做......

IEnumerable<string> digits  = Enumerable.Range(0, 10) // 0-9
.Select(i => i.ToString());
//Create a query for starts with on each digit.
IEnumerable<IQueryable<Question>> questions = digits
.Select(i => dbcontext.Questions.Where(q => q.StartsWith(i))
IQueryable<Question> concatedTogether = .Aggregate(Queryable.Concat) //Union all each of them together
int count = concatedTogether.Count();

或者简单地

int count = Enumerable.Range(0, 9)
.Select(int.ToString)
.Select(i => dbcontext.Questions.Where(q => q.StartsWith(i))
.Aggregate(Queryable.Concat)
.Count();

关于sql - 数字匹配的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23512223/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com