根据字符串列表获取 SQL LINQ 结果

本文关键字:SQL LINQ 结果 获取 列表 字符串 | 更新日期: 2023-09-27 18:36:34

让我们从将用于过滤结果的字符串列表开始:

 List<String> RadioNames = new List<String>();
 RadioNames.AddRange(new String[] { "abc", "123", "cba", "321" });

我希望能够根据RadioNames过滤 LINQ to SQL 数据库表,但问题是我希望RadioNames是部分匹配(这意味着它将捕获 Radio123 而不仅仅是 123)。

我需要过滤的来源如下:

var ChannelGrants = from cg in sddc.ChannelGrants
                    select new
                    {
                        cg.ID,
                        cg.Timestamp,
                        cg.RadioID,
                        cg.Radio
                    };

所以我需要执行类似于下面的事情(在原始ChannelGrants结果之外,因为这是一个条件搜索)

 if(RadioNamesToSearch != null)
 {
      List<String> RadioNames = new List<String>();
      // Here I split all the radio names from RadioNamesToSearch based on a command separator and then populate RadioNames with the results
      ChannelGrants = from cg in ChannelGrants
                      where ???
                      select cg;
 }

我需要帮助???上面的代码(或者如果ChannelGrants = ...一起无效)。重复上面,我需要过滤ChannelGrants以从RadioNames返回任何匹配项,但它会进行部分匹配(这意味着它将捕获 Radio123 而不仅仅是 123)。

所有代码都包含在一个方法中,因此...

 public static DataTable getBrowseChannelGrants(int Count = 300, String StartDate = null, String StartTime = null, String EndDate = null, String EndTime = null, String RadioIDs = null, String RadioNamesToSearch = null, String TalkgroupIDs = null, String TalkgroupNames = null, bool SortAsc = false)

根据字符串列表获取 SQL LINQ 结果

您将 ChannelGrants 中的哪个字段与 RadioNames 进行比较?

若要检索仅在无线电名称列表中的条目,请使用如下所示的包含方法

ChannelGrants = from cg in ChannelGrants
                  where RadioNames.Contains(cg.Radio)
                  select cg;

(如果要在 Radio 属性中查找具有其中一个无线电名称的所有行。 更换 cg。带有您要匹配的相应列的收音机)

如果您在 SQL 中有 this where 子句,这会给您类似的结果

where cg.Radio in ("abc", "123", "cba", "321")

从这个链接 如何在 Linq 中像 % 一样做 SQL?看起来你也可以用类似的匹配来组合它,但添加斜杠,这不是我个人做过的事情。

代替???

RadioNames.Where(rn=>cg.Radio.ToLower().Contains(rn.ToLower())).Count() > 0

那应该可以做到...

当然,ToLower() 调用是可选的。

编辑:我刚刚写了这个,它在控制台应用程序中对我来说工作得很好。结果包含一个项目,WriteLine吐出"cbaKentucky"。不知道该告诉你什么。

class Program
{
    static void Main(string[] args)
    {
        List<String> RadioNames = new List<String>();
        RadioNames.AddRange(new String[] { "abc", "123", "cba", "321" });
        List<ChannelGrants> grants = new List<ChannelGrants>();
        grants.Add(new ChannelGrants() { ID = 1, Radio = "cbaKentucky", RadioID = 1, TimeStamp = DateTime.Now });
        var result = from cg in grants
                  where RadioNames.Where(rn=>cg.Radio.ToLower().Contains(rn.ToLower())).Count() > 0
                  select cg;
        foreach (ChannelGrants s in result)
        {
            Console.WriteLine(s.Radio);
        }
    }
}
class ChannelGrants
{
    public int ID { get; set; }
    public DateTime TimeStamp { get; set; }
    public int RadioID { get; set; }
    public string Radio { get; set; }
}

目前,似乎没有最好的方法,所以我会回答这个问题,直到一个新的答案不重复在这个线程上不起作用的其他答案。