How to do SQL Like % in Linq?

前端 未结 14 1491
误落风尘
误落风尘 2020-11-22 13:46

I have a procedure in SQL that I am trying to turn into Linq:

SELECT O.Id, O.Name as Organization
FROM Organizations O
JOIN OrganizationsHierarchy OH ON O.Id         


        
相关标签:
14条回答
  • 2020-11-22 14:25

    Try this, this works fine for me

    from record in context.Organization where record.Hierarchy.Contains(12) select record;
    
    0 讨论(0)
  • 2020-11-22 14:25
    System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")
    
    0 讨论(0)
  • 2020-11-22 14:29

    Contains is used in Linq ,Just like Like is used in SQL .

    string _search="/12/";
    

    . . .

    .Where(s => s.Hierarchy.Contains(_search))
    

    You can write your SQL script in Linq as Following :

     var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});
    
    0 讨论(0)
  • 2020-11-22 14:31
    .Where(oh => oh.Hierarchy.Contains("/12/"))
    

    You can also use .StartsWith() or .EndsWith().

    0 讨论(0)
  • 2020-11-22 14:38

    I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

    from o in dc.Organization
    join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
    where oh.Hierarchy.Contains(@"/12/")
    select new { o.Id, o.Name }
    

    or

    from o in dc.Organization
    where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
    select new { o.Id, o.Name }
    

    Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
    Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

    0 讨论(0)
  • 2020-11-22 14:40

    Way late, but I threw this together to be able to do String comparisons using SQL Like style wildcards:

    public static class StringLikeExtensions
    {
        /// <summary>
        /// Tests a string to be Like another string containing SQL Like style wildcards
        /// </summary>
        /// <param name="value">string to be searched</param>
        /// <param name="searchString">the search string containing wildcards</param>
        /// <returns>value.Like(searchString)</returns>
        /// <example>value.Like("a")</example>
        /// <example>value.Like("a%")</example>
        /// <example>value.Like("%b")</example>
        /// <example>value.Like("a%b")</example>
        /// <example>value.Like("a%b%c")</example>
        /// <remarks>base author -- Ruard van Elburg from StackOverflow, modifications by dvn</remarks>
        /// <remarks>converted to a String extension by sja</remarks>
        /// <seealso cref="https://stackoverflow.com/questions/1040380/wildcard-search-for-linq"/>
        public static bool Like(this String value, string searchString)
        {
            bool result = false;
    
            var likeParts = searchString.Split(new char[] { '%' });
    
            for (int i = 0; i < likeParts.Length; i++)
            {
                if (likeParts[i] == String.Empty)
                {
                    continue;   // "a%"
                }
    
                if (i == 0)
                {
                    if (likeParts.Length == 1) // "a"
                    {
                        result = value.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    }
                    else // "a%" or "a%b"
                    {
                        result = value.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    }
                }
                else if (i == likeParts.Length - 1) // "a%b" or "%b"
                {
                    result &= value.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%b%c"
                {
                    int current = value.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    int previous = value.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                    result &= previous < current;
                }
            }
    
            return result;
        }
    
        /// <summary>
        /// Tests a string containing SQL Like style wildcards to be ReverseLike another string 
        /// </summary>
        /// <param name="value">search string containing wildcards</param>
        /// <param name="compareString">string to be compared</param>
        /// <returns>value.ReverseLike(compareString)</returns>
        /// <example>value.ReverseLike("a")</example>
        /// <example>value.ReverseLike("abc")</example>
        /// <example>value.ReverseLike("ab")</example>
        /// <example>value.ReverseLike("axb")</example>
        /// <example>value.ReverseLike("axbyc")</example>
        /// <remarks>reversed logic of Like String extension</remarks>
        public static bool ReverseLike(this String value, string compareString)
        {
            bool result = false;
    
            var likeParts = value.Split(new char[] {'%'});
    
            for (int i = 0; i < likeParts.Length; i++)
            {
                if (likeParts[i] == String.Empty)
                {
                    continue;   // "a%"
                }
    
                if (i == 0)
                {
                    if (likeParts.Length == 1) // "a"
                    {
                        result = compareString.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    }
                    else // "a%" or "a%b"
                    {
                        result = compareString.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    }
                }
                else if (i == likeParts.Length - 1) // "a%b" or "%b"
                {
                    result &= compareString.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%b%c"
                {
                    int current = compareString.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                    int previous = compareString.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                    result &= previous < current;
                }
            }
    
            return result;
        }
    }
    
    0 讨论(0)
提交回复
热议问题