How do I use Like in Linq Query? - linq

How I can use Like query in LINQ ....
in sql for eg..
name like='apple';
thanks..

Use normal .NET methods. For example:
var query = from person in people
where person.Name.StartsWith("apple") // equivalent to LIKE 'apple%'
select person;
(Or EndsWith, or Contains.) LINQ to SQL will translate these into the appropriate SQL.
This will work in dot notation as well - there's nothing magic about query expressions:
// Will find New York
var query = cities.Where(city => city.Name.EndsWith("York"));

You need to use StartsWith, Contains or EndsWith depending on where your string can appear. For example:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will find all cities that start with "Lo" (e.g. London).
var query = from c in ctx.Customers
where c.City.Contains("York")
select c;
will find all cities that contain "York" (e.g. New York, Yorktown)
Source

name.contains("apple");

I use item.Contains("criteria"), but, it works efficiently only if you convert to lower both, criteria and item like this:
string criteria = txtSearchItemCriteria.Text.ToLower();
IEnumerable<Item> result = items.Where(x => x.Name.ToLower().Contains(criteria));

Related

Like condition in LINQ

I am relatively new to LINQ and don't know how to do a Like condition. I have an IEnumerable list of myObject and want to do something like myObject.Description like 'Help%'. How can I accomplish this? Thanks
Look here:
http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx
Snippet:
StartsWith and Contains:
var query = from c in ctx.Customers
where c.City.StartsWith("L") && c.City.Contains("n")
select c;
And if you should use it with LINQ to SQL (does not work with LINQ to Objects):
Custom LIKE (System.Data.Linq.SqlClient.SqlMethods.Like):
var query = from c in ctx.Customers
where SqlMethods.Like(c.City, "L_n%")
select c;
You generally use the exact same syntax you'd use outside a query.
myObject.Description.StartsWith("Help")
Whether this actually works depends on where you're using LINQ (it might either be ran as code, in which case everything works, or get converted to something like else, such as SQL, which might have limitations), though, but it's always worth a try.
You can use StartsWith, EndsWith, or Contains depending where you want to check:
var result = from o in myCollection
where o.Description.StartsWith("Help")
select o;
You can optionally pass a StringComparison to specify whether to ignore case or not (for StartsWith and EndsWith) which would make the operation behave more like a SQL query:
var result =
from o in myCollection
where o.Description
.StartsWith("Help", StringComparison.InvariantCultureIgnoreCase))
select o;
If you want to do a case insensitive contains, you need to use IndexOf instead:
var result =
from o in myCollection
where o.Description
.IndexOf("Help", StringComparison.InvariantCultureIgnoreCase) > 0
select o;
you can use string.StartsWith or string.EndsWith or string.Contains property of string to use it as Like Operator.
Startswith will work for Like 'A%'
Endswith will work for Like '%A'
Contains will work like '%A%'

Linq to EF Expression Tree / Predicate int.Parse workaround

I have a linq Entity called Enquiry, which has a property: string DateSubmitted.
I'm writing an app where I need to return IQueryable for Enquiry that have a DateSubmitted within a particular date range.
Ideally I'd like to write something like
IQueryable<Enquiry> query = Context.EnquirySet.AsQueryable<Enquiry>();
int dateStart = int.Parse("20090729");
int dateEnd = int.Parse("20090930");
query = (from e in query
where(enq => int.Parse(enq.DateSubmitted) < dateEnd)
where(enq => int.Parse(enq.DateSubmitted) > dateStart)
select e);
Obviously Linq to EF doesn't recognise int.Parse, so I think I can achieve what I want with an Expression method that returns a predicate???
I've been playing around with PredicateBuilder and looking all over but I've successfully fried my brains trying to work this out. Sure I could add another property to my Entity and convert it there but I'd really like to understand this. Can anyone explain or give an example/link that doesn't fry my brains?
Thanks in advance
Mark
If you know your date strings are valid, and they're really in that order (which is a natural sort order) you might be able to get away with string comparisons:
IQueryable<Enquiry> query = Context.EnquirySet.AsQueryable<Enquiry>();
string dateStart ="20090729";
string dateEnd = "20090930";
query = (from e in query
where(enq => enq.DateSubmitted.CompareTo(dateEnd)) < 0)
where(enq => enq.DateSubmitted.CompareTo(dateStart)) > 0)
select e);

Can Distinct be expressed using so-called embedded query rather than a method call

given the following code:
string[] colors = {"red","green","blue","red","green","blue"};
var distinctColors = (from c in colors select c).Distinct();
distinctColors.Dump();
Is it possible to fold the call .Distinct() into the embedded query syntax?
something like int T-SQL
select distinct color from TableofColors
C#'s query expression syntax doesn't include "distinct". VB's does, however - for example, from the MSDN docs for VB's Distinct clause:
// VB
Dim customerOrders = From cust In customers, ord In orders _
Where cust.CustomerID = ord.CustomerID _
Select cust.CompanyName, ord.OrderDate _
Distinct
The C# equivalent would have to explicitly call Distinct() in dot notation.
However, your example can still be simplified:
string[] colors = {"red","green","blue","red","green","blue"};
var distinctColors = colors.Distinct();
distinctColors.Dump();
Don't think you have to use query expressions to use LINQ :)
There's no distinct embedded query syntax in C# as far as I'm aware. This is as close as it gets:
var distinctColors = (from color in colors
select color).Distinct()
Query comprehension syntax does not support the Distinct method.
In your case, you could simply write colors.Distinct(); you're not doing anything with the query expression.
You can try this
var dis = from c in colors
group c by c;
foreach (var cVal in dis)
{
string s = cVal.Key;
}

Building Dynamic LINQ Queries based on Combobox Value

I have a combo box in Silverlight. It has a collection of values built out of the properties of one of my LINQ-to-SQL objects (ie Name, Address, Age, etc...). I would like to filter my results based off the value selected in a combo box.
Example: Say I want everyone with a last name "Smith". I'd select 'Last Name' from the drop down list and enter smith into a textbox control. Normally I would write a LINQ query similar to...
var query = from p in collection where p.LastName == textbox.Text select p;
Is it possible to decide the property dynamically, maybe using Reflection? Something like
var query = from p in collection where p.(DropDownValue) == textbox.Text select p;
Assuming:
public class Person
{
public string LastName { get; set; }
}
IQueryable<Person> collection;
your query:
var query =
from p in collection
where p.LastName == textBox.Text
select p;
means the same as:
var query = collection.Where(p => p.LastName == textBox.Text);
which the compiler translates from an extension method to:
var query = Queryable.Where(collection, p => p.LastName == textBox.Text);
The second parameter of Queryable.Where is an Expression<Func<Person, bool>>. The compiler understands the Expression<> type and generates code to build an expression tree representing the lambda:
using System.Linq.Expressions;
var query = Queryable.Where(
collection,
Expression.Lambda<Func<Person, bool>>(
Expression.Equal(
Expression.MakeMemberAccess(
Expression.Parameter(typeof(Person), "p"),
typeof(Person).GetProperty("LastName")),
Expression.MakeMemberAccess(
Expression.Constant(textBox),
typeof(TextBox).GetProperty("Text"))),
Expression.Parameter(typeof(Person), "p"));
That is what the query syntax means.
You are free to call these methods yourself. To change the compared property, replace this:
typeof(Person).GetProperty("LastName")
with:
typeof(Person).GetProperty(dropDown.SelectedValue);
Scott Guthrie has a short series on dyamically built LINQ to SQL queries:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
That's the easy way...then there's another way that's a bit more involved:
http://www.albahari.com/nutshell/predicatebuilder.aspx
You can also use the library I created: http://tomasp.net/blog/dynamic-linq-queries.aspx. You would store the properties in ComboBox as lambda expressions and then just write:
var f = (Expression<Func<Product, string>>)comboBox.SelectedValue;
var query =
from p in collection
where f.Expand(textBox.Text)
select p;

Does LINQ Support Composable "OR Queries"?

In another posting: Does Linq-To-Sql support composable queries there was discussion on how to compose/concat where clauses dynamically. This appears to be done with an "AND" (i.e. the first where clause and the second where clause are joined by an AND). What I am wondering is if there is a way to compose Linq queries with an OR.
Example:
var people = from p in Person
where p.age < 18
select p
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
This gives people with a first name of "Daniel" and that are under 18. I'm looking for the syntax to join these to find people who have a first name of "Daniel" or are under 18.
Note: I am using ADO.net Data Services so I do not have .Contains() available to me.
EDIT: The Union Suggestion (by Garry Shutler) is exactly what I am looking for functionality-wise. I did run into two possible issues with it:
It looks like it would make multiple database hits if I was to do a third condition (union seems to take an IEnumerable as its parameter) - I was hoping to build up multiple AND and OR statements in code and then execute one request.
Union is not supported by ADO.Net Data Services (very disappointing)
Is what you want as simple as:
var people = from p in Person
where p.age < 18 || p.firstName == "Daniel"
select p;
or have you just given a simple example?
In which case you can use:
var under18 = from p in Person
where p.age < 18
select p;
var daniels = from p in Person
where p.firstName == "Daniel"
select p;
var combined = under18.Union(daniels);
LinqToSql may be intelligent enough to convert that to an OR but I'm not so sure.
What about using PredicateBuilder by Joe Albahari?
var predicate = PredicateBuilder.False<Person>();
predicate = predicate.Or(p => p.age < 18);
predicate = predicate.Or(p => p.firstName == "Daniel");
var query = Person.Where(predicate);
The predicate option is the way to go. The Union option DOES NOT build good sql. Reference http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/925b245d-5529-4a64-8cd4-4bc83ee6fe7a/
I wrote about how to achieve queries which search for a key value within a set on my blog .
Here are the relevant links.
Contains Operations in ADO.NET Data Services Part I
Contains Operations in ADO.NET Data Services Part II
Using this , you can write queries which look like this
//The set in which we have to search for a match
List<string> citiesIWillVisit = new List<string>() {"London","Berlin","Prague"};
var customersAround = nwContext.Customers
.IsIn<Customers>(citiesIWillVisit, c=> c.City);
foreach (Customers localCustomer in customersAround) {
System.Console.WriteLine(localCustomer.ContactName);
}

Resources