从字符串列表中获取SQL LINQ结果

时间:2012-06-06 22:41:03

标签: c# linq-to-sql

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

 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)

3 个答案:

答案 0 :(得分:0)

代替???

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

答案 1 :(得分:0)

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

要检索仅在您的RadioNames列表中的条目,您可以使用像这样的contains方法

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

(如果你想找到Radio属性中有一个RadioNames的所有行。用你匹配的相应列替换cg.Radio)

如果你在SQL

中有这个where子句,这会给你一个类似的结果
where cg.Radio in ("abc", "123", "cba", "321")

来自此链接How to do SQL Like % in Linq? 看起来你也可以像匹配一样组合它,但是添加斜线,这不是我亲自做过的事情。

答案 2 :(得分:0)

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