简体   繁体   English

LINQ to SQL查询字符串StartsWith来自通用列表的元素

[英]LINQ to SQL query where a string StartsWith an element from a generic list

I'm looking to update one of my queries as the requirements for the search has changed. 我正在寻找更新我的一个查询,因为搜索的要求已经改变。 Originally, the user was to enter a single SKU and a mfg. 最初,用户要输入单个SKU和制造商。 date range to search the product catalog. 日期范围以搜索产品目录。 So this is what I used. 所以这就是我用过的东西。

DateTime startDate = ...;
DateTime endDate = ...;
string prodSKU = TextSKU.Text.Trim();

var results = from c in db.Products
                where c.is_disabled == false 
                && c.dom >= startDate 
                && c.dom <= endDate 
                && c.sku.StartsWith(prodSKU)
                select c;

Now the requirement says that the user can enter a comma delimted list of SKUs into the textbox to search. 现在要求说用户可以在文本框中输入逗号分隔的SKU列表进行搜索。 What I'm stumped about is how to find all the products in the mfg. 我很难过的是如何在制造商中找到所有产品。 date range that begin with any of the SKUs in skuList (w/o using a fornext loop). 以skuList中的任何SKU开头的日期范围(没有使用fornext循环)。

string prodSKU = TextSKU.Text.Trim();
List<string> skuList = prodSKU.Split(new char[] { ', ' }).ToList();

var results = from c in db.Products
                where c.is_disabled == false 
                && c.dom >= startDate 
                && c.dom <= endDate 
                // && c.sku.StartsWith(prodSKU)
                select c;

Any ideas would be greatly appreciated! 任何想法将不胜感激!

Something like 就像是

string prodSKU = TextSKU.Text.Trim(); 
List<string> skuList = prodSKU.Split(new char[] { ', ' }).ToList();  

var results = from c in db.Products                 
   where c.is_disabled ==false                  
   && c.dom >= startDate                  
   && c.dom <= endDate                  
   &&  skuList.Any(sl=>c.sku.StartsWith(sl))                 
      select c; 
string prodSKU = TextSKU.Text.Trim();
List<string> skuList = prodSKU.Split(new char[] { ', ' }).ToList();

var results = from c in db.Products
                where c.is_disabled == false 
                && c.dom >= startDate 
                && c.dom <= endDate 
                &&  skuList.Contains(c.sku)
                select c;

EDIT: I'll put this here even though this question is already answered. 编辑:即使这个问题已经回答,我也会把它放在这里。

I achieved the same as the accepted solution, but using an extension method to aid readability: 我实现了与已接受的解决方案相同的功能,但使用扩展方法来提高可读性:

public static class StringExtensions
{
    public static bool StartsWithAny(this string s, IEnumerable<string> items)
    {
        return items.Any(i => s.StartsWith(i));
    }
}

and then the solution is: 然后解决方案是:

var results = from c in db.Products
            where c.is_disabled == false 
            && c.dom >= startDate 
            && c.dom <= endDate 
            && c.sku.StartsWithAny(skuList)
            select c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM