LINQ To SQL 包含区分大小写的搜索

本文关键字:大小写 搜索 包含区 To SQL LINQ | 更新日期: 2023-09-27 18:31:09

当我使用以下查询时,它会完美地获得结果。但它区分大小写。这是我的代码:

    IQueryable<article> results;
    if (rrbAuthor.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where a.author.Contains(textBox1.Text) select a).Distinct();
    else if (rrbKeywords.IsChecked)
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where k.word.Contains(textBox1.Text) select a).Distinct();
    else
        results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid where a.title.Contains(textBox1.Text) select a).Distinct();
    ListArticles(results, 1);

如何在敏感的情况下获得结果?

LINQ To SQL 包含区分大小写的搜索

您可以使用

ToLower()方法将字符串转换为小写,然后进行比较
您还可以在 oder 中使用空传播来避免在某些stirngs为 null 的情况下出现NullReference异常。

尝试关注

  IQueryable<article> results;
  if (rrbAuthor.IsChecked)
    results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
               where a.author?.ToLower().Contains(textBox1.Text?.ToLower()) == true
               select a).Distinct();
  else if (rrbKeywords.IsChecked)
    results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
               where k.word?.ToLower().Contains(textBox1.Text?.ToLower()) == true
               select a).Distinct();
  else
    results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid
               where a.title?.ToLower().Contains(textBox1.Text?.ToLower()) == true
               select a).Distinct();
  ListArticles(results, 1);
您可以使用

.ToUpper() 或 .ToLower() 两面:

    results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid 
where a.author.ToUpper().Contains(textBox1.Text.ToUpper()) select a).Distinct();

    results = (from a in _db.articles join k in _db.keywords on a.id equals k.aid 
where a.author.ToLower().Contains(textBox1.Text.ToLower()) select a).Distinct();