【问题标题】:Linq case insensitive joinLinq 不区分大小写连接
【发布时间】:2015-06-19 03:57:10
【问题描述】:

我想实现两件事。

首先,我希望此连接不区分大小写。

我过去使用过这种不区分大小写的 where 子句

where b.foo.Equals(foo, StringComparison.OrdinalIgnoreCase)

但我现在不知道,如何在join中使用它。

其次,我想返回包含作者姓名和书籍数量的元组。

        var query = from b in Books
                    join a in authors on b.Author equals a
                    select Tuple.Create(a, _count_of_authors_books_);

        return query;

谢谢。

【问题讨论】:

  • 尝试使用string.equals

标签: c# linq join case-insensitive


【解决方案1】:

Linq 仅支持 equi-joins,但您可以将每个操作数转换为一种或另一种情况:

    var query = from b in Books
                join a in authors on b.Author.ToLower() equals a.ToLower()
                select Tuple.Create(a, _count_of_authors_books_);

    return query;

请注意,这在某些文化中可能会产生一些有趣的结果;如果这是一个问题,那么另一种性能较差的方法是使用相等过滤器进行交叉连接:

    var query = from b in Books
                from a in authors 
                where String.Compare(b.Author, a, true) == 0
                select Tuple.Create(a, _count_of_authors_books_);

    return query;

【讨论】:

  • String.Compare 也很“不错”,因为它可以处理空值。
【解决方案2】:

回答这个问题有点晚了,但根据OrdinalIgnoreCase 上的文档:

OrdinalIgnoreCase 属性返回的StringComparer 将要比较的字符串中的字符视为使用不变区域性的约定转换为大写,然后执行与语言无关的简单字节比较。

那么这将是等效的连接:

var query = from b in Books
            join a in authors on b.Author.ToUpperInvariant() equals a.ToUpperInvariant()
            select Tuple.Create(a, _count_of_authors_books_);

return query;

【讨论】:

    【解决方案3】:

    Linq 是否 支持不区分大小写的匹配,但不支持查询语法。您需要使用Method Syntax

    var query = Books.Join(
        authors, // the other list
        book => book.Author, // what to compare in "Books"
        author => author, // what to compare in "authors"
        (book, author) => Tuple.Create(author, _count_of_authors_books_), // what to select at the end
        StringComparer.InvariantCultureIgnoreCase); // how to do the comparison
    

    StringComparer 有一些其他变体,使用你需要的那个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2016-08-28
      • 2015-06-14
      • 1970-01-01
      • 2021-07-05
      • 2015-01-22
      相关资源
      最近更新 更多