How to return all values of a column as null except one column value in LINQ? - linq

I want to return only one column value and other column values as null from database. how can i do that in LINQ? also have to make values of not nullable fields to null while retrieving

C#
var results = from item in db.items
select (item.col1 == value ? item.col1 : null);
VB.NET
Dim results = From item in db.items
Select iif(item.col1 == value ? item1.col : Nothing)

Related

Add a Null column to a linq query

I want to do a LINQ query and add in a column that is null. Something like this:
var query = (from all in data
select new
{
all.Column1,
all.Column2,
all.Column3,
newColumn = null
})
However, this gives me the error "cannot assign null to anonymous type property".
Add the null with appropriate cast depending on the type of newColumn such as e.g. newColumn = (string) null;

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

Case When Variable Is null then is null

In my sql query I'm having this where condition:
WHERE
parentID = prj.parent_id
and mandator_fk = mandator_id
The variable parentID is null as default.
If this variable is null the WHERE condition should be parentID is null and not like in the query above (parentID = prj.parent_id). If this variable is filled the WHERE condition should be parentID = prj.parent_id.
How can I perform this with only one sql query?
EDIT: its inside a function, thats why I would have only one sql query for this.
This is not working I know that, but this is like what I need:
WHERE
CASE
WHEN parentID is null THEN parentID is null
ELSE
parentID = prj.parent_ID
END
and mandator_fk = mandator_id
TIA
frgtv10
Seems you want to join on nulls, so you'll need to convert them first. Try this:
where
NVL(parentId, 0) = NVL(prj.parent_id, 0)
and ...
I'm not sure if NVL() function is surgable, so here is another way to write the condition:
WHERE
( parentID = prj.parent_id
OR parentID IS NULL AND prj.parent_id IS NULL
)
AND mandator_fk = mandator_id

Linq query with two sub-queries that group by, one with an average, and one with a max

I have a parent table, parentTable which may or may not have children in childTable. I am looking to get average % complete of any given parent's children, and the MAX(due) (date) of the children where they exist. My SQL is this:
SELECT parentRecord_id, assigned_to,
(SELECT avg(complete)
FROM childTable
WHERE parent_id = parentRecord_id
and deleted IS NULL
GROUP BY parent_id),
(SELECT max(due)
FROM childTable
WHERE parent_id = parentRecord_id
and deleted IS NULL
GROUP BY parent_id
)
FROM parentTable s
WHERE s.deleted IS NULL and assigned_to IS NOT NULL
My result set gives me rows with either correct values for the average and max, or null. In this instance I have to do follow up processing so I could ignore the null values if I was doing a foreach through DataTable rows. However I am trying to do this in Linq and can't figure out how to avoid a System.InvalidOperationException where Linq is trying to cast null to a double. Here is what I've tried so far.
var query8 = from s in db.parentTable
where s.deleted == null
select new
{
ID = s.assigned_to,
Average =
((from t in db.childTable
where t.parent_id == s.strategy_id
group t by new { t.parent_id } into g
select new
{
a0 = g.Average(f0 => f0.complete )
}).FirstOrDefault().a0)
};
foreach (var itm in query8)
{
Console.WriteLine(String.Format("User id:{0}, Average: {1}", itm.ID, itm.Average));
}
Here's my question. How do I get the query to handle those returned rows where average complete or max due (date) are null?
You can either filter out the records where the values are null (by another condition) or if you want to include them do something like this:
a0 = g.Average(f0 => f0.complete.HasValue? f0.complete: 0 )
I would cast the list to nullable double before calling Average/Max like so:
var query8 =
from s in db.parentTable
where s.deleted == null
select new
{
ID = s.assigned_to,
Average =
from t in db.childTable
where t.parent_id == s.strategy_id
group t by t.parent_id into g
select g.Cast<double?>().Average(f0 => f0.complete)
};
Assuming complete is a Nullable, you should be able to do:
var query8 = from s in db.parentTable
where s.deleted == null
select new
{
ID = s.assigned_to,
Average =
((from t in db.childTable
where t.parent_id == s.strategy_id
&& s.complete.HasValue()
group t by new { t.parent_id } into g
select new
{
a0 = g.Average(f0 => f0.complete )
}).FirstOrDefault().a0)
};
Thanks to all who responded.
I was unable get around the null anonymous issue with the basic query as I had it, but adding a join to the childTable eliminated the nulls.
Another solution is to use a from x in g.DefaultIfEmpty clause.
var query8 =
from st in db.tableParent
select new { Ass = st.assigned_to ,
Avg =
(from ta in db.tableChild
group ta by ta.parent_id into g
from x in g.DefaultIfEmpty()
select g.Average((f0=>f0.complete))).FirstOrDefault()
};

How can i write query record in table have parentID with condition parentID == 0 and ID != (parentID)

Here i my LINQ query to get record in Table Menu with condition are parentID == 0(get root menu) and ID != (parentID list) (which is parent ID list is are id of menu record that have child), i just want to load all record includes root menu that have no children record and children record :
List<Menu> menus = MenuDAO.Instance.GetAll(); // Get All Record in Menu Table
var parentID = (from p in menus where p.ParentID != 0 select new {p.ParentID}).Distinct(); // Get unique ParentID in Menu Table
List<int> numParentID = new List<int>();
foreach (var a in parentID)
{
numParentID.Add(a.ParentID);
} // assign to a list <int>
this.ddlMenu.DataSource = from m1 in menus
where !(numParentID).Contains((int)m1.ID) && m1.ParentID == 0
select new { m1.ID, m1.Name };
this.ddlMenu.Databind();
And i run this code , i display record that have no children, do not display chilren record. Somebody help me fix it. My new in LINQ , thanks a lot.
The Result as i expect here is : list of record that do not have any children, my Menu table schema is : ID, Name, Order, ParentID.
Suggestions
1-You don't need to select an anonymous object in the first select, you could write as
var parentIDs = (from p in menus
where p.ParentID != 0
select p.ParentID).Distinct();
always a good practice to name collections as plural (parentIDs)
2-No need to iterate to create a new List<>, so you can write all of them in one query
List<int> numParentIDs = (from p in menus
where p.ParentID != 0
select p.ParentID).Distinct().ToList();
Answer :
first select all the leaf level children IDs. Get all ID except the values in the ParentID column. And then do a select from menu by joining the leafIDs
var leafMenuIDs = menus
.Select(m => m.ID)
.Except(menus.Select(m => m.ParentID).Distinct())
.Distinct();
this.ddlMenu.DataSource = from m in menus
join id in leafMenuIDs on m.ID equals id
select new { m.ID, m.Name };

Resources