LINQ搜索列表

时间:2018-03-16 06:29:45

标签: c# linq

我有这个清单

var allPlaces = new[]
{
    new { Name = "Red apple", OtherKnownNames = "Green" },
    new { Name = "Orange", OtherKnownNames = "" },
    new { Name = "Banana", OtherKnownNames = "the" },
}.ToList();

我的查询是"苹果"

我的代码没有返回第一个和第三个项目,查询有2个单词用空格分隔,我希望查询中的任何单词以Name开头或者应该返回OtherKnownName。

var query = "the apple";
var queryParts = query.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

var filteredList =
    allPlaces
        .Where(p =>
            p.Name
                .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                .Any(pp => queryParts.Any(qp => qp.StartsWith(pp)))
            || p.OtherKnownNames
                .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                .Any(pp => queryParts.Any(qp => qp.StartsWith(pp))))
        .ToList();

1 个答案:

答案 0 :(得分:0)

假设您要忽略大小写,并接受与查询单词开头匹配的名称(基于您的StartsWith示例)。

使用扩展方法进行拆分而不使用空条目:

public static string[] SplitNoEmpty(this string s, params char[] seps) => s.Split(seps, StringSplitOptions.RemoveEmptyEntries);

您可以简单地拆分query字符串并搜索匹配项:

var qwords = query.SplitNoEmpty(' ');

var ans = allPlaces.Where(p => qwords.Any(qw => (p.Name + " " + p.OtherKnownNames).SplitNoEmpty(' ')
                                                                                  .Any(nw => qw.StartsWith(nw, StringComparison.CurrentCultureIgnoreCase))
                                     )
                   )
                   .ToList();