Currently, i have a table with the data Fruits, grade and price. The grade available in my table are A , B and C. Please look at the code snippet. As what you can see, i put D in the where filter. I suppose the query will be null. But after i run the code, the program prompt the "Not Null? WTH?". So, may i know whats in the query and how to detect the D if it's not in the table?
p/s: i'm newbie
C# code snippet:
var query = (from p in db
where p.grade == "D"
select p.price).ToArray();
if (query == null)
System.Console.WriteLine("You get Null in the query");
else if (query != null)
System.Console.WriteLine("Not Null? WTH?");
Since you are doing ToArray, it will never be null. You may check the length.
if(query.Length <= 0)
Or even better if you do:
var query = (from p in db
where p.grade == "D"
select p.price).Count();
if(query > 0)
or
var ifItemExist = (from p in db
where p.grade == "D"
select p.price).Any();
Or shorter:
var ifItemExist = db.Any(p=> p.grade == "D");
You don't get null because this method will still return an array. The array will be empty, but the array will not be null. (This is in fact why null exists... it is to differentiate between a "zero" value and the absence of a value.
If you want to test if there are any elements in the result you can use:
if (query.Any())
Actually, it is not null, it's returning an empty array which is different from null.
alternately, you can do this,
int query = (from p in db
where p.grade == "D"
select p.price).Count();
if (query > 0)
{
System.Console.WriteLine("Found");
}
else
{
System.Console.WriteLine("Not Found");
}
Related
I want to get the records with "Restricted" at top.
here Is my query:
var records = (from entry in db.Table1
orderby entry.Always_Prohibited
select new
{
RowID = entry.RowID,
VehicleMake = entry.Make,
VehicleModel = entry.Model,
Restricted = (entry.Always_Prohibited == null || entry.Always_Prohibited == "False") ? "Restricted" : "Not Restricted"
}).ToList();
I tried by Orderby but it is not working because entry.Always_Probibited is a string field.
Please suggest me.
If you have only two values, simply order descending:
from entry in db.Table1
orderby entry.Always_Prohibited descending
If you have more, assign integer values to your strings:
from entry in db.Table1
orderby entry.Always_Prohibited=="A" ? 0 : entry.Always_Prohibited=="B" ? 1 : 2 // and so on
As a side note, strings are a pretty terrible way of storing state in databases. You should redesign it to store it as well defined integers (preferably as foreign keys in master lookup tables, ie strongly typed enums).
User then below give code. It will help to you.
var records = (from entry in db.Table1.AsQueryable();
orderby entry.Always_Prohibited
select new
{
RowID = entry.RowID,
VehicleMake = entry.Make,
VehicleModel = entry.Model,
Restricted = (entry.Always_Prohibited == null || entry.Always_Prohibited == "False") ? "Restricted" : "Not Restricted"
}).ToList();
I don't understand what is wrong in this syntax.
tags="abc,xyz,asdf"
List<string> ta= tags.Split(',').ToList<string>();
List<string> demo = from T in db.tokens where ta.Contains(T.tname) select T.Id;
I have table with tags and their ids in it.I need to gets ids of the tags from the table...
Thank You
EDIT::
I have changed it to something like this.And its working and another problem
List<int> demo = from T in db.tokens where ta.Contains(T.tname) select T.Id).ToList();
var slist = from I in db.institutes
from T in db.inst_to_token
where I.CountryId == cont
&& demo.Contains(T.tokenid)
select I;
But the above is showing this error at the where condition
The best overloaded method match for System.collection.generic.List.Contains(int) has some invalid arguments
Since T.tokenid is an int?, you need to select inst_to_token where tokenid is not null and pass T.tokenid.Value to demo.Contains method
var slist = from I in db.institutes
from T in db.inst_to_token
where I.CountryId == cont
&& T.tokenid.HasValue
&& demo.Contains(T.tokenid.Value)
select I;
I am using LINQ to select a list based on a particular condition. The attribute value is stored in byte array, which is later encrypted while storing in the database table. I want to using this attribute in my SELECT LINQ query now, but it is throwing the following exception when I try to:
LINQ to Entities does not recognize the method 'Byte[] GetBytes(System.String)' method, and this method cannot be translated into a store expression.
This is the code that I using:
var result = (from history in context.Histories
where history.ID == Id &
(history.Salary != null || history.Salary != Encoding.ASCII.GetBytes("0"))
select (DateTime?)history.Date).Max();
return result;
I want to select the date from the history table, of those id's whose salary is either not equal to null or 0. How can I change this?
Just get the bytes first :
var bytes = Encoding.ASCII.GetBytes("0");
var result = (from history in context.Histories
where history.ID == Id &
(history.Salary != null || history.Salary != bytes)
select (DateTime?)history.Date).Max();
return result;
Change your code to:
var bytes = Encoding.ASCII.GetBytes("0");
var result = (from history in context.Histories
where history.ID == Id &
(history.Salary != null || history.Salary != bytes)
select (DateTime?)history.Date).Max();
return result;
LINQ can't evaluate your GetBytes when it translates your query to SQL
Never used LINQ within C# before until 30 mins ago and am struggling to find an answer to my query online (probably due to my lack of understanding).
I have a simple query
var variableName = from a in tableName.AsEnumerable()
where a.column1 == item1
&& a.column2 == item2
&& a.column3 != null
select a;
The SQL column is defined as an int, null.
When the code encounters a record that is null on the database for column3, the following error is generated "the value for column3 in table <tableName> is DBNull".
Instead of checking for != null, i guess i should be using something else, but have attempted checking for DBNull.Value but the compiler states "Operation != cannot be applied to operands of type int and system.DBNull".
Any ideas?
This looks like a typed dataset, which : yeuch - stop using those, but I digress.
As such, accessing a.column3 will always raise an exception if that value is DBNull. You would need to use the typed-dataset pattern:
&& !c.Iscolumn3Null()
tableName.AsEnumerable() makes the query in-memory, so all table rows are downloaded from DB and the conditions are checked on application.
Try that:
var variableName = from a in tableName
where a.column1 == item1
&& a.column2 == item2
&& a.column3 != null
select a;
It should be translated into an SQL query and download only necessary rows.
Try this..
var variableName = from a in tableName.AsEnumerable()
where a.column1 == item1
&& a.column2 == item2
&& a.column3 != dbnull.value
select a;
try
var variableName = from a in tableName.AsEnumerable()
where a.column1 == item1
&& a.column2 == item2
&& !DBNull.Value.Equals(a.column3)
select a;
edit apparently I need to read up on typed data sets :) and why I should never use them
I am trying to import data into a new database, but some of the columns in the old database are null.
In one of my methods, I am using the query below to get the records, like I said already there is a column in the rows which has a null value for some records.
Guid nameGuid= new guid('CCECE54B-EE14-4463-8A0B-02C72679334A')
MySubQuery = from a in MainQuery
where a.Table1.Id.Equals(nameGuid)
Select a;
I want to check for a.Table1.Id value, if it is equal to null, then I still want the row but ignore the where condition.
Any suggestion for using the ternary operator in Linq query or any other approaches for my task.
Sounds like you want:
MySubQuery = from a in MainQuery
where a.TableId.Id Is Nothing OrElse a.Table1.Id.Equals(nameGuid)
That's assuming my VB is correct... in C# I'd just write:
var query = from a in mainQuery
where a.TableId.Id == null || a.TableId.Id == nameGuid
select a;
or using the extension method directly:
var query = mainQuery.Where(a => a.TableId.Id == null ||
a.TableId.Id == nameGuid);
How about:
MySubQuery = from a in MainQuery
where a.Table1.Id == null || a.Table1.Id.Equals(nameGuid)
select a;
Or am I missing something?
EDIT:
The thing I am missing is what Mr Skeet spotted. It's VB. Well, I'll let this stick around as a C# sample.
var datarows = (from row in dt.AsEnumerable()
where row.Field<Guid>("Id") == new
Guid(ddlCode.SelectedValue.ToString())
select row);
After that
DataTable newDt=datarows.CopyToDataTable();
var sampleName=newDt.Rows[0]["SampleName"].ToString();