How to improve linq query and remove in clause - linq

I have a linq query
var query = from record in session.Query<Record>()
from brwSet in session.Query<BorrowerSet>()
from brw in session.Query<Borrower>()
where
brw.PrintOrder == 1 && brwSet.PrintOrder == 0
&& record.Package.BorrowerSet.Contains( brwSet )
&& brwSet.Borrower.Contains( brw )
select new Summary()
{
BorrowerFirstName = brw.Contact.FirstName,
BorrowerLastName = brw.Contact.LastName,
LoanPackageID = record.Id
};
how could I rewrite this to eliminate the extra from clauses
from brwSet in session.Query<BorrowerSet>()
from brw in session.Query<Borrower>()
how can I rewrite this so I don't need the contains function on these collections?
record.Package.BorrowerSet.Contains( brwSet ) && brwSet.Borrower.Contains( brw )

This query doesn't have Contains.
var query =
from record in session.Query<Record>()
from brwSet in record.Package.BorrowerSet
where brwSet.PrintOrder == 0
from brw is brwSet.Borrowers
where brw.PrintOrder == 1
select new Summary()
{
BorrowerFirstName = brw.Contact.FirstName,
BorrowerLastName = brw.Contact.LastName,
LoanPackageID = record.Id
};

Related

Dynamic where condition LINQ

I have a problem with my code. I don't know how I can insert in my selection all equals conditions of:
codicielementipartizione.sezione == el[i].ToString()
dynamically from
codicielementipartizione.sezione == el[1].ToString()
to
codicielementipartizione.sezione == el[el.count - 1].ToString()
Tn this code:
var selection = (from codicielementipartizione inlistacodici.cep
where codicielementipartizione.uno == 1 &&
codicielementipartizione.sezione == el[i].ToString()
select codicielementipartizione).ToList();
You can make the fixed part of the query which will be IQueryable. After that you can add your conditions as such.
Fixed part:
var query = from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1;
Dynamic part:
foreach(var condition in el)
query = query.Where(codicielementipartizione.sezione == el.ToString());
Query execution:
var result = query.Select().ToList();
Maybe you mean this:
var selection = (from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1
&& el.Select(i => i.ToString()).Contains(codicielementipartizione.sezione)
select codicielementipartizione).ToList();

Dynamic where condition in linq query expression

My Code :
IEnumerable<DataRow> whrRowEnum;
whrRowEnum = from r in dtInput.AsEnumerable()
where r.Field<string>("EMP_DEP") == "DEP1"
orderby EMP_DEP
select r;
The above code is working fine due to hard coded where condition, but In run-time I need to add multiple where condition in my linq query like r.Field("EMP_DEP") == "DEP1" && r.Field("EMP_ID") == "EMP1"
You can use lambda syntax to compose your query based on conditions:
IEnumerable<DataRow> query = dtInput.AsEnumerable();
if (condition1)
query = query.Where(r => r.Field<string>("EMP_DEP") == "DEP1");
if (condition2)
query = query.Where(r => r.Field<string>("EMP_ID") == "EMP1");
var whrRowEnum = query.OrderBy(r => r.Field<string>("EMP_DEP"));
Another option is adding conditions to query filter
whrRowEnum = from r in dtInput.AsEnumerable()
where (!condition1 || (r.Field<string>("EMP_DEP") == "DEP1")) &&
(!condition2 || (r.Field<string>("EMP_ID") == "EMP1"))
orderby EMP_DEP
select r;

Distinct keyword in linq query

my linq query returns duplicate records like below, how i have to use distinct keyword in this linq query.
var draft_recieved = from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
};
.Distinct() has to be applied as an extension method.
var draft_recieved = (from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
}).Distinct();

Joining to a GROUP'ed query

I'm a LINQ Newb and I've got this query, which returns the pages in a survey. (These values are not materialized into a table, for whatever reason.)
//Group all of this data by page
var pages = from fq in db.FormQuestions
where (fq.FormId == id) && fq.Disabled == false
group fq by fq.PageNumber into p
select new DTOs.PageDTO { PageNumber = p.Key.Value };
And then I have this query, which projects all of the leaf-data into DTOs.
var questions = from fq in db.FormQuestions
join q in db.Questions on fq.QuestionId equals q.QuestionId
where (fq.FormId == id) && fq.Disabled == false
//where (fq.FormId == id) && fq.Disabled == false && fq.PageNumber == page
orderby fq.DisplayOrder
select new DTOs.FormQuestionDTO()
{
DisplayOrder = (fq.DisplayOrder.HasValue ? fq.DisplayOrder.Value : 0),
PageNumber = (fq.PageNumber.HasValue ? fq.PageNumber.Value : 0),
QuestionId = q.QuestionId,
QuestionSelectionMode = q.vts_tbQuestionSelectionMode.Description,
QuestionText = q.QuestionText,
Answers =
from answer in q.Answers
join at in db.AnswerTypes on answer.AnswerTypeId equals at.AnswerTypeID
where answer.Disabled == false
orderby answer.DisplayOrder
select new DTOs.AnswerDTO()
{
AnswerId = answer.AnswerId,
AnswerText = answer.AnswerText,
DisplayOrder = answer.DisplayOrder,
AnswerType = at.Description
}
};
Is there a way to join these two neatly? I.e., under each page DTO I want to see the QUestion DTOs, then inside of that Answer DTOs, and onward...
Also, even if I could do this all in one LINQ statement, is it preferable to build the LINQ statements separately and then merge them? This feels a bit like building temp variables in SQL in that it may be possible to build one giant query but it's a pain to maintain.
So why wouldn't something like this work?
//Group all of this data by page
var pages = from fq in db.FormQuestions
where (fq.FormId == id) && fq.Disabled == false
group fq by fq.PageNumber into p
select new DTOs.PageDTO {
PageNumber = p.Key.Value
questions = from fq in db.FormQuestions
join q in db.Questions on fq.QuestionId equals q.QuestionId
where (fq.FormId == id) && fq.Disabled == false
orderby fq.DisplayOrder
select new DTOs.FormQuestionDTO()
{
DisplayOrder = (fq.DisplayOrder.HasValue ? fq.DisplayOrder.Value : 0),
// etc as you 2nd code sample

How would I write this dynamic linq query?

Basically I want to write a linq query to order the number of days they were present. But I have got these six time filters- Today,Yesterday,current month,previous month,current year,previous year.So now I have this queries which I have simplified but before these queries below, I actually order these employees on different aspects and after ordering it as you can see I assign rank and then at the same time find out his count(which may or may not be used to rank them later)-
var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
{
EmployeeId=k.Employee.Id,
CompanyId=Employee.Company.Id
PresentCount=(from e in employeeAttendance
where d.RecNum == k.recnum
&& d.date_present.Year == DateTime.Today.Year
&& d.date_present.Month == DateTime.Today.Month
&& d.date_present.Day == DateTime.Today.Day
select d).Count()
}
So now when the filter is say previous year I have -
var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
{
Position=
EmployeeId=k.Employee.Id,
CompanyId=Employee.Company.Id
PresentCount=(from e in employeeAttendance
where d.RecNum == k.recnum
&& d.date_present.Year == (DateTime.Today.Year-1)
}
and if have it on Current Month I have -
var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
{
EmployeeId=k.Employee.Id,
CompanyId=Employee.Company.Id
PresentCount=(from e in employeeAttendance
where d.RecNum == k.recnum
&& d.date_present.Month == DateTime.Today.Month
&& d.date_present.Year == DateTime.Today.Year
}
I basically want to combine all these in one query with basically having like a dynamic clause for finding out the present count ?
Just create a simple wrapper. Eg:
IQueryable<EmployeeDTO> GetEmployeeCount(Expression<Func<DateTime, bool>> pred)
{
var result=datacontext.Employee(c=>c.Company.Id==companyId).
Select((k, index) => new EmployeeDTO()
{
EmployeeId=k.Employee.Id,
CompanyId=Employee.Company.Id,
PresentCount=(from e in employeeAttendance
where d.RecNum == k.recnum && pred(d.date_present)
select d).Count()
});
return result;
}
Usage:
var r = GetEmployeeCount(d => d.Year == (DateTime.Today.Year-1));
var r = GetEmployeeCount(
d => d.Month == DateTime.Today.Month && d.Year == DateTime.Today.Year);

Resources