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%'
Related
Is there a way to build on to the select clause of a previously defined LINQ query?
For example:
var stuffQuery =
from stuff in MyStuff
select new {
stuff.Name
};
var query2 =
from stuff in stuffQuery
join otherStuff in YourStuff on stuff.Name equals otherStuff.Name
select new {
stuff.*, // how can I accomplish this?
YourStuff = new {
otherStuff.PropertyX
}
};
The result I want is an object like:
string Name
anonymous YourStuff
string PropertyX
I thought about using a "Combine" method which would reflectively combine my two anonymous objects into a dynamic. But Linq-to-Sql won't know what to do with the method.
Instead, I think I need a method which returns the select expression. Its parameters would be the first Queryable, and the select expression for the second Queryable. Something like:
var query2 =
from stuff in stuffQuery
join otherStuff in YourStuff on stuff.Name equals otherStuff.Name
GetCombinedSelectClause(stuffQuery, new {
YourStuff = new {
otherStuff.PropertyX
}
});
How can I accomplish this? I'm not married to any particular syntax-style. However, I'd prefer not to use a string-based solution (such as System.Linq.Dynamic).
How about ExpandoObject? I believe it can do exactly what you need.
My question probably isn't worded the best it could be. However, I do not think LINQ queries were designed to accomplish the goal I was after.
I'm closing the question because I simply do not think the answer is achievable.
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));
Seems like I may have missed something simple in the syntax, but I'd like to get the results of FirstOrDefault from a linq statement directly without having to store the IEnumerable in a temporary variable first. Something like this:
var bestCar = from c in cars
orderby c.Price
select first c
I know the first keyword doesn't actually exist but illustrates what I'd like to do. I also know I can wrap the from...select statement in parenthesis and call FirstOrDefault directly but I think the above syntax is cleaner and easier to read.
Enumerable.FirstOrDefault is one of the extension methods in the Enumerable class which does not have a corresponding LINQ syntax element. The only way to bind to this method is via method call syntax.
You can avoid the temporary by doing the follownig
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
There isn't a way to do that. LINQ is used for defining a query. Doing that doesn't actually cause an evaluation, whereas executing FirstOrDefault (or enumerating over it) executes the query.
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault()
OR
var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
Sorry I didn't read your question entirely, it seems that this may be exactly what you don't want to do.
In VB you can use 'Aggregate':
Dim BestCar = Aggregate c In cars
Order By c.Price
Into FirstOrDefault
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;
}
I'm trying to wrap my head around linq -> nhib
I have a simple bit of sql that i'm trying to get working in nhibernate.linq
select * from
ColModel where ColModel.DataIndex
not in ('CostElement1', 'CostElement2', 'CostElement3')
and ColModel.ReportId = 1
The list of excluded DataIndex values comes in in the form of a List<string> called excludeNames
Here is what I have tried but it seems that it's not really feeling the love:
var s = base._sessionManager.OpenSession();
var query = from col in s.Linq<ColModel>()
where col.Report.Id == reportid &&
!(from c in s.Linq<ColModel>() select c.DataIndex).Contains(excludeNames)
select col;
return query.ToList();
the error:
The type arguments for method 'System.Linq.Enumerable.Contains<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I'm pretty sure I'm borfing this from the offset so any pointers would be well appreciated :)
w://
Contains doesn't accept a list.
There are ways to work around this in LINQ, but I'm not sure which, if any, of those will work in NH Linq
I think you have your exclusion backwards.
s = base._sessionManager.OpenSession();
var query = from col in s.Linq<ColModel>()
where col.Report.Id == reportid &&
!excludeNames.Contains(col.DataIndex)
select col;
return query.ToList();
Collection.Contains(item) will produce the SQL item in (...collection...), adding the negation will get you what you want.