'And' operator in Linq - linq

I have a query that prints userid in label1 when username is entered.Works fine; but i want to write query for username and password that prints userid. so how can i write it? i tried writing using 'and' operator but dont seems to work.
int id = (from auser in lq.logins
where auser.username == userNameString //&& auser.Password =pwdString
select auser.userid).SingleOrDefault();
label1.Text = id.ToString();
Thanks
Ani

It looks like you used the assignment operator = instead of the comparison operator ==. The query should be:
int id = (from auser in lq.logins
where auser.username == userNameString && auser.Password == pwdString
select auser.userid).SingleOrDefault();
label1.Text = id.ToString();

It probably doesn't work becase you used = instead of ==.

Related

Linq Where Clause Change based on Parameters

I have a linq statement that returns a list of records based on where clause
This where clause checks for two parameter values.
Out of which one parameter is optional.
so i need a suggestions if i can switch my where clause based on the optional Parameter
something like this
if(locid==0)
{
where (p.CustomerID == custid)
}
else{
where (p.CustomerID == custid) & (p.LocationID == locid )
}
can any one help me how can i get this work.
thanks
You could try writing it like this:
where (p.CustomerID == custid) && (locid == 0 || p.LocationID == locid )
Yes - queries can be composed (although you don't need this for this particular case as #rsbarro pointed out):
var query = p;
if(locid==0)
query = query.Where( p =>p.CustomerID == custid);
else
query = query.Where( p =>p.CustomerID == custid & p.LocationID == locid);
//any other conditions
As BrokenGlass mentioned, you should use composition:
IQueryable<Foo> query = unfiltered.Where(p => p.CustomerID == custId);
if (locid != 0)
{
query = query.Where(p => p.LocationID == locid);
}
Note that the query is not executed until you start reading data from it, so you needn't worry about this making multiple requests.
It looks like in your original post you were trying to use query syntax piecemeal - that won't work, but the "dot notation" is pretty simple here. You can always create your initial query using a query expression if you want - again, that query won't be executed immediately anyway.

LINQ query result in int type variable

I want the the LINQ query result in int type variable.
i have a query this will always return the single int value. i want result sumthing like that.
int interlineId = from cSInterline in codeShareInterline_.AsEnumerable()
where cSInterline.Field<int>("InterCodeId") == interCodeId[0]
select cSInterline.Field<int>("PermitedPercent");
But it returning the error..
Your query is returning an IEnumerable<int>, with only one item in this case. So add Single or SingleOrDefault onto the end to return only that 1 item. If your query might return more than 1 item then use FirstOrDefault.
int interlineId =
(from cSInterline in codeShareInterline_.AsEnumerable()
where cSInterline.Field<int>("InterCodeId") == interCodeId[0]
select cSInterline.Field<int>("PermitedPercent")).SingleOrDefault();
Try this:
int interlineId = (from cSInterline in codeShareInterline_.AsEnumerable()
where cSInterline.Field<int>("InterCodeId") == interCodeId[0]
select cSInterline).Single().Field<int>("InterCodeId");
Try this (it should work):
int? interlineId = (from cSInterline in codeShareInterline_.AsEnumerable()
where cSInterline.Field<int>("InterCodeId") == interCodeId[0]
select cSInterline.Field<int>("PermitedPercent")).FirstOrDefault();

In Operator in Linq

I tried to use the suggestion provided here for using In operator in linq but, i am not able to convert my requirement into LINQ statement.
Below is the SQL query which i need to convert to Linq
select *
from navigator_user_field_property
where user_id = 'albert'
and field_id in (
select field_id
from navigator_entity_field_master
where entity_id = 1
and use_type = 0)
order by field_id
I want this to be converted to a Efficient Linq.
Most of the answers deal with the predetermined list of string array which is not working in my case.
Thanks
Looks like a join to me:
var query = from navigator in db.NavigatorUserFieldProperties
where navigator.UserId == "albert"
join field in db.NavigatorEntityFieldMasters
.Where(f => f.EntityId == 1 && f.UseType == 0)
on navigator.FieldId equals field.FieldId
select navigator;
Note that this will return the same value multiple times if there are multiple fields with the same ID - but I suspect that's not the case.
You could do a more literal translation like this:
var query = from navigator in db.NavigatorUserFieldProperties
where navigator.UserId == "albert" &&
db.NavigatorEntityFieldMasters
.Where(f => f.EntityId == 1 && f.UseType == 0)
.select(f => f.FieldId)
.Contains(navigator.FieldId)
select navigator;
... and that may end up translating to the same SQL... but I'd personally go with the join.
Here is an efficient and readable LINQ query:
var fields =
from field in db.navigator_entity_field_masters
where field.entity_id == 1 && field.user_type == 0
select field;
var properties =
from property in db.navigator_user_field_properties
where property.user_id == "albert"
where fields.Contains(property.field)
select property;
Look mama!! Without joins ;-)

LINQTOSql Missing parameter question

I have a long LinqtoSQl query in which several parameters I'm not forcing the user to specify anything. I started using a Select Case statement that would test rather or not a parameter string's length > 0 or if it's an int > 0. But I realized that I would have to test for each possibility and create queries based on each.
I did some searching and ran across a post in which the person answering the post was saying to negate a portion of the query use ||. After doing some more searching (and realizing with little c# skills I do have || is the OR conditional), I realized that wouldn't help me.
I guess what I want to do is something like
Dim r = From x in db.List _
(if firstName.Length < 1 then ignore query
else)where x.firstName = firstName _
(if lastName.Length < 1 then ignore query
else)where x.LastName = lastName _
Select x
I knw there has to be a better way than IfElse'ing my way through this...I was about to do some funky stuff with a StringBuilder, but I'm not sure it would "fire", ie:
Dim sb as New StringBuilder
sb.Append("Dim r = From x in db.List _")
If firstName.Length < 1 then
sb.Append("Where x.firstName = firstName")
ughh, please tell me there's a better way...
Thanks for your help!
Use the fact that queries are composable. I'll write this in C# to start with, then translate it into VB afterwards if you need that. The principle would be the same.
IQueryable<YourEntityType> query = db.List;
if (firstName != "")
{
query = query.Where(x => x.firstName == firstName)
}
if (lastName != "")
{
query = query.Where(x => x.lastName == lastName)
}
Now just read from query appropriately. (I've changed the nature of the string conditions just because it simpler to understand "is this string the empty string" than "is this string's length greater than 0" - both will work, obviously.)
Note that you can't do this sort of conditional call in a query expression, but it's easy when you're just calling the extension methods explicitly.
How about...
Dim r = From x in db.List _
where (x.firstName = firstName Or firstName = "") _
And (x.LastName = lastName Or lastName = "") _
Select x

linq like empty string

var list = (from i in _dataContext.aspnet_Users.Include("aspnet_Membership") where i.UserName.Contains(userName) select i ).ToList();
if userName="" then nothing return. how can i do that if empty string then return all records?
Do:
var list =
(from i in _dataContext.aspnet_Users.Include("aspnet_Membership")
where string.IsNullOrEmpty(userName)
|| i.UserName.Contains(userName)
select i ).ToList();
Fun Fact: The System.Data.Linq.SqlClient namespace includes a few helper methods that are pretty useful.
You can use the SqlMethods.Like function which will return all results if an empty string is passed to it.
Ex:
(from i in _dataContext.aspnet_Users.Include("aspnet_Membership")
where SqlMethods.Like(i.UserName, "%" + userName + "%")
select i).ToList();

Resources