Linq - customized column - linq

select ID, 0 as Index from Table;
How do I do this query in linq?
var o = From X in Table Select X.ID, (0 as Index) <- error

var o = from x in Table select new { ID = X.ID, Index = 0 };
The new keyword here creates a new anonymous type that gets exposed by the query. The first property, ID, is populated by the ID property from X. The second property, Index, is given the static value of 0.

Related

LINQ Syntax for query using Sum()

I want to calculate a Sum value using fields from 2 tables and can't work out the syntax.
var x = (from l in context.Lessons
join t in context.Tariffs on l.TariffId equals t.Id
where l.StudentSemesterId == studentSemesterId
select new {
lessonCost = (t.Rate) * (l.Duration / 60)
});
This returns a set of values for individual lessons. How do I get the Sum total of these lessons?
You are selecting a new IEnumerable of an anonymous object type. Just select the correct value you are looking for. Then you have IEnumerable of float/double/decimal/whatever. Then take the resulting sum of that query.
var x = (from l in context.Lessons
join t in context.Tariffs on l.TariffId equals t.Id
where l.StudentSemesterId == studentSemesterId
select (t.Rate) * (l.Duration /60)).Sum();

Sorting issue with LINQ query and join using tables from different databases

I'm having trouble writing my LINQ query.
Here's the scenario:
I have 2 databases: A and B
In database A: I have a tableX which has the following fields: Employee ID, Name, Address, Phone, ..., Active
In database B: I have a tableY which has the following fields: Employee ID, Visible, Order
the number of records in table Y is less than or equal to the number of records in table X.
Basically, I need to extract the employee records from table X who have the attribute 'Visible' (in table Y) set to True and would like to sort them using the 'Order' attribute.
This is what I have so far:
ADataContext dbA = new ADataContext();
BDataContext dbB = new BDataContext();
//Get the list of records from tableY where 'Visbile' is set to True
var List = dbB.tableY
.Where(x => x.Visible == true).OrderBy(x => x.Order)
.ToList();
//Extract the list of employee IDs
IEnumerable<int> ids = List.Select(x => x.EmployeeID).Distinct();
var employees = dbA.tableX
.Where(x => ids.Contains(x.EmployeeID) && x.Active == true)
.ToList();
I'm able to get the correct list of employees, but cannot figure out how to apply the sorting order (present in tableY) on tableX
Currently, regardless of the order specified in tableY, the records returned from tableX are sorted as they were entered in the table (oldest to most recent).
Any ideas how I can fix my query.
Thanks,
I've re-written it all as a single query:
var employees =
from x in dbA.tableX
where x.Active
from y in dbB.tableY
where x.EmployeeID == y.EmployeeID
orderby y.Order
select x;

row number with help of linq

my table consists of 3 columns(sno,name,age) now i am retrieving this table from the database with extra column(row number) ,i used the following code
select * from (
select ROW_NUMBER() over (order by SNo asc)as rowindex,SNo,Name,Age
from tblExample)
as example where rowindex between ((pageindex*10)+1) and ((pageindex+1)*10)
note:here pageindex is the varaible that takes some intger value which is passed by the user
my data base is sql server 2008, now i want to write the same query using linq
can any one please change the abovesql query into linq. iam unable to do it as iam new to linq. iam struck up with this problem please help me thank you in advance
You can write query as beow
var index=1;
var pageIndex=1;
var pageSize = 10;
data.Select(x => new
{
RowIndex = index++,
Sno = x.Sno,
Name = x.Name,
Age = x.Age
}).OrderBy(x => x.Name)
.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

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