使用LINQ在字符串列中搜索字符串列表

本文关键字:字符串 搜索 列表 使用 LINQ | 更新日期: 2023-09-27 17:51:13

所以我使用实体框架和linq,但我使用的是函数方法。

假设我有一个这样的ID列表:

List<string> bids = { "33", "44", "55", "66" }; // this is what the split ends up

但在数据库中,我有一个名为"BuildingID"的字符串列,存储为逗号分隔的值。"query"是IQueryable<构建表>。

        List<string> bids = search_string_full_of_comma_bids.Split(';').ToList();
        query = query.Where(t => bids.Contains(t.BuildingIDs));
        //query = query.Any(t => t.BuildingIDs.Contains(bids); // Loop needed.
        return query;

因此,我想搜索"BuildingID"数据库字符串,看看它是否有任何"search_string_full_of_comma_bids">

正在数据库中构建表:

project 1 | pname = 'building complex #1' | BuildingIDs = '33;54;42;56;21;56;32;'
project 2 | pname = 'building complex #2' | BuildingIDs = '77;42;31;12;33;'

但我的搜索查询可能是"33"或"77"。。。搜索"33"将同时提供这两个选项。搜索"54;31"将同时提供这两个选项。

因此,标准的SQL查询应该是这样的:

SELECT * FROM BuildingTable WHERE BuildingIDs LIKE '%54%' OR BuildingIDs LIKE '%31%'.

不幸的是,我不能在Linq中添加一堆"OR"。

使用LINQ在字符串列中搜索字符串列表

List<string> bids = search_string_full_of_comma_bids.Split(';').ToList();
        query = query.Where(t => bids.Any(b=> 
                               t.BuildingIDs.StartsWith (b+";") //if it's in the start
                              || t.BuildingIds.EndsWith (";" + b) //end 
                              || t.BuildngIds.Contains(";" + b + ";") //;id;
                              ));

你可以试试这样的东西,但这太难看了。您应该使用表,而不是将ID保存在字符串中。

考虑到你的数据,你可能根本不需要.EndsWith,通常你会在最后一个末尾没有";"时使用它。

我同意@tim-s的观点,因为数据结构是这里问题的原因,然而,我创建了一个搜索扩展nuget包,可以帮助解决这个问题。NinjaNye.SearchExtensions将使您能够执行以下操作:

using NinjaNye.SearchExtensions;
...
List<string> bids = search_string.Split(';').Select(b => ";" + b + ";");
query = query.Search(t => ";" + t.BuildingIDs + ";").Containing(bids)

这将只返回包含任何所提供的BuildingIDs

的记录