LIKE query with Entity Framework [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to do SQL Like % in Linq?
Like Operator in Entity Framework?
I'm doing a query like this:
var matches = from m in db.Customers
where m.Name == key
select m;
But I don't need m.Name to be exactly equal to key. I need m.Name to be like key.
I can't find how to recreate the SQL query:
WHERE m.Name LIKE key
I'm using SQL Server 2008 R2.
How to do it?
Thanks.

Would something like this linq query work for you.. ?
var matches = from m in db.Customers
where m.Name.Contains(key)
select m;
this should also work I edited my answer.
Contains is mapped to LIKE '%#p0%' which is case insensitive

var matches = from m in db.Customers
where m.Name.StartsWith(key)
select m;
Make the search and compare whether the string is either lowercase or uppercase to get the best result since C# is case-sensitive.
var matches = from m in db.Customers
where m.Name.ToLower().StartsWith(key.ToLower())
select m;

Related

Possible to "flatten" linq output into a period delimited list? [duplicate]

This question already has answers here:
How do I create a comma delimited string from an ArrayList?
(8 answers)
Closed 4 years ago.
I have a key-value pair array that contains an LDAP distinguished name, and I want to retrieve the DNS domain name of the host. (Only the DC's not the fqdn)
Assume that the LDAP parsing is done correctly, and the DC entries when combined constitute the DNS domain name of the host.
Given the code below, is it possible to convert
DC = my
DC = domain
DC = com
into
my.domain.com
I could use a for...each with a stringbuilder but it doesn't feel elegant. Is there a better way?
My code is below:
var kvList = ParseDistinguishedName(ldapName);
StringBuilder sb = new StringBuilder();
var names = (from k in kvList
where k.Key == "DC"
select k.Value);
Very easily, fortunately: string.Join does exactly what you want:
var dotSeparated = string.Join(".", names);
You might want to consider using method calls rather than a query expression for such a simple query, mind you. What you've got is precisely equivalent to:
var names = kvList.Where(k => k.Key == "DC").Select(k => k.Value);
The query expression is fine, but can end up being verbose for simple queries. (Query expressions really shine with let, join etc - anything that introduces transparent identifiers.)
Probably something like this:
kvList.Where(x => x.Key == "DC")
.Select(x => x.Value)
.Aggregate((x,y) => x + "." + y)

Santax for Joins using Linq/lambda & Nhibernate

Originally I had this linq statement:
refusedZones = session.Query<ZoneBO>().Where(x => x.StateId == _config.RefusedStateId).ToList();
Works fine and I get my list with business objects. I now need to change this query, I still want my list of strongly typed business objects back, but I have to do a join with another table.
I have tested this SQL query and it works the way I want it to:
select z.ZoneName, z.ZoneSerial from zone z join transactionzone tz on z.ZoneId = tz.ZoneId where z.StateId = 3 and tz.StateId = 16
My question is how do I do this in linq with a Lambda expression? I assume it will start like this...
var refusedZones = session.Query<ZoneBO>().Join(.......expression here....).ToList();
Can anyone help me with the santax please, very new to linq, finding it confusing.
You will need to add a reference from Zone to TransactionZone. How have you setup your mappings?
Once you have a reference setup it is unnecessary to explicitly write the joins in LINQ.
You can do this:
session.Query<ZoneBO>()
.Where(x => x.State.Id == 3 && x.TransactionZone.State.Id == 16)
.ToList()

LINQ Equivalent of SELECT DISTINCT

I'm wanting to only display a list of CourseNo with no duplicates using LINQ, but I can't quite figure the syntax out.
this.Distinct_CourseNo = (from c in Roster_Sections
select c).Distinct(CourseNo).ToList;
The SQL equivalent would be something along the lines of:
SELECT DISTINCT CourseNo
FROM Roster_Sections
All the provided answers are applicable only if you have moreLINQ. However, you can try this instead:
this.Distinct_CourseNo = (from c in Roster_Sections
group c by c.CourseNo into g
select g.First()).ToList();
using select c will include all columns in the Roster_Sections, thus Distinct() will not work if atleast one row in a column is different from the other row.
this.Distinct_CourseNo = (from c in Roster_Sections
select c.CourseNo).Distinct().ToList();
or
this.Distinct_CourseNo = Roster_Sections.Distinct(c => c.CourseNo).ToList();
You’d pass Distinct a lambda describing what defines distinctness:
this.Distinct_CourseNo = Roster_Sections.Distinct(x => x.CourseNo).ToList();
If you mean to get a list of unique course numbers as opposed to a list of unique courses based off course number, 今 草 顿 웃’s answer is the way to go.

Linq not contains dynamic query [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Linq to SQL “not like” operator
How can I write a dynamic linq query with using not contains?
I use .Contains() instead of like. But what should I use instead of not like?
just use ! before the contains condition. Like
var myProducts = from p in products
where !productList.Contains(p.ID)
select p;
Some thing like this should help...
YourDataContext dc = new YourDataContext();
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
Use ! operator. Like this:
private List<int> iList = new List<int>
{
1,2,3,4,5,6,7,8,9
};
if (!iList.Contains(888))
{
}

Linq to SQL - Query

I am trying to mimic below statement in Linq to SQL.
WHERE (rtrim(posid) like '%101' or rtrim(posid) like '%532')
I statement basically determine if posid ends with 101 or 532. In the above example I am only making 2 comparisons but their could be 1 to N comparisons all joined with OR. I store the comparison values (101,532,...) in a generic list that I send to my Linq to SQL method.
I have tried to mimic above SQL using a where clause unsuccessfully (example below):
var PosNum = new List<string>();
PosNum.Add("101");
PosNum.Add("532");
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => PosNum.Contains(p.posid.Trim()));
The issue with the above where clause is that it tries to do an exact match rather I want an ends with comparison.
How would I mimic the SQL statement in Linq to SQL.
Thank You in advance for any help / advice you can provide.
I would use String.EndsWith();
This will check the end of the string rather than entire contents of it.
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => p.posid.EndsWith("102") || p.posid.EndsWith("532"));
In EF 4 you can use the StartsWith / EndsWith methods by now. Might also work in LINQ to SQL.
UPDATE
Just realized that you are trying todo this against multiple values (PosNum), I don't think that this is directly supported currently. You can however concatenate multiple Where()clauses to get the result.
UPDATE 2
As AdamKing pointed out concatenating the where clauses was filtering against all PosNum values, here is the corrected version:
var baseQuery = (from a in context.tbl_sspos select a);
IEnumerable<YourType> q = null;
foreach(var pos in PosNum)
{
if(q == null)
q = baseQuery.Where(a => a.posid.EndsWith(pos));
else
q = q.Union(baseQuery.Where(a => a.posid.EndsWith(pos)));
}
This is not as pretty anymore, but works nonetheless.

Categories