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

时间:2016-01-19 12:51:19

标签: c# linq case-sensitive

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

    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);

如何设置在敏感案例中获得结果?

2 个答案:

答案 0 :(得分:2)

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

尝试以下

  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);

答案 1 :(得分: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();