I got about 5 look-a-like linq querys just like this SortPerson() metod. I'm trying to develop a search using dropdowns where a user can select values from the dropdown and returns the values that are true from one or more dropdowns the user has selected to use.
Is there a simpler way to develop this? help would be much appreciated
public void SortPerson()
{
var personId = ddlPerson.SelectedValue;
var data = new MyModelContext();
var documents = from d in data.tblDocuments
join sp in data.tblPersons on d.DocPerson equals sp.PersonId
select d;
if (!String.IsNullOrEmpty(personId))
{
documents = documents.Where(c => c.DocPerson.Equals(personId));
}
rptResult.DataSource = documents.ToList();
rptResult.DataBind();
}
I don't see the point in joining without Where if you still select only one table.
If you want all document in case when Person is not selected, then you can't create much simpler method. You can write it shorter like:
var documents =
from d in data.tblDocuments
join ...
where String.IsNullOrEmpty(personId) || d.DocPerson equals personId
select d;
so you don't need separate if statement.
If you want to use several values from 5 dropdowns and use them as conditions in single query, just add more conditions:
var personId = ddlPerson.SelectedValue;
var someValue = ddlSomeDDL.SelectedValue;
//3 more values from DDL
var documents = from d in data.tblDocuments
join sp in data.tblPersons on d.DocPerson equals sp.PersonId
where (String.IsNullOrEmpty(personId) || sp.PersonId equals personId)
&& (String.IsNullOrEmpty(someValue) || d.SomeColumn equals someValue)
//3 more conditions
select d;
Related
I am able to select data from two tables, But I am getting partial result only while retrieving data from three tables.
var items = from orders in nobleappDbContext.JobOrders.Where(m => m.OrderStat == 0)
join users in nobleappDbContext.users on orders.Uid equals users.Uid
join customers in nobleappDbContext.customers on users.Uid equals customers.Uid into customdata
from m in customdata.DefaultIfEmpty()
select new
{
Eid = orders.Eid,
Uid = orders.Uid,
OrderStat = orders.OrderStat,
Name = m.Name,
Contact = (m.Contact == null) ? 0 : m.Contact
};
return Ok(items);
With this code, I am getting only result (common result) from users table and I am looking for something like UNION or OUTER JOIN.
Any help will be highly appreciated
finally I got exactly what I was looking for, here by posting the answer as I might help someone looking for same. LEFT JOIN with Entity Framework is the key
var query = from a in authurs
join b in books on a.Id equals b.AuthorId into auth_books
from left in auth_books.DefaultIfEmpty()
join bs in booksSeries on left.BookSeriesId equals bs.Id into books_bookseries
from left2 in books_bookseries.DefaultIfEmpty()
select new
{
Author = a.Name,
Book = left.Name,
BookSeries = left2.Description
};
var resList2 = query.ToList();
refer this link for further clarification.
the below query is written in sql to select the recent activity of an salesperson based on last activity date
select UDV.User_dailyActivityId,UDV.userId,UDV.[DATE] ActivityDate,UDV.Activity,UDV.Subject
From [SalesTrack].[dbo].[UserDailyActivity] UDV,
(
Select userId,Max([DATE]) ActivityDate from [SalesTrack].[dbo].[UserDailyActivity]
Group by userId
) GPUDV
where udv.userId = GPUDV.userId and UDV.[DATE] = gpudv.ActivityDate
order by udv.userId,UDV.[DATE]
i have to change the above query into linq, i am newbie in linq
i succeed writing the inline query part
var lastgroup=(from ua in db.UserDailyActivities group ua by ua.userId into GPua select new{GPua,ActivityDate=GPua.Max(ua=>ua.date)});
Please help me to finish the whole query
Maybe something like this:
var result=
(
from UDV in db.UserDailyActivity
from GPUDV in
(
from inner in db.UserDailyActivity
group inner by inner.userId into g
select new
{
userId=g.Key,
ActivityDate=g.Max (x =>x.DATE)
}
).Where (w =>w.userId==UDV.userId && w.ActivityDate==UDV.DATE)
select new
{
UDV.User_dailyActivityId,
UDV.userId,
ActivityDate = UDV.[DATE],
UDV.Activity,
UDV.Subject
}
).ToList();
where db is the linq data context
Sorry to pester with a simple problem but I'm stumped with a simple select on an HTML5 WebSQL Data Base.
Table tPhones has id, hid, location and several other columns. I would like to return a list of rows with where hid = [input value] or, if no rows with that hid exist, return rows where hid = 1.
I have tried LIMIT 1 ACS etc but that too fails.
Function showPhones(){
var phonegroup = $(this).attr("id");
var hid = localStorage.hid;
db.transaction (function(transaction)
{
var sql = "SELECT * FROM tPhones WHERE dept ='"+phonegroup+"' AND ((hid ='"+hid+"') OR IFNULL (hid ='1')) ORDER BY location ASC";
transaction.executeSql (sql, undefined,function(transaction,result)
{…………..rest of function working fine
Any help would be much appreciated.
A normal expression in the WHERE clause can access only columns of the current record.
To check for the existence of any other record, you have to use a subquery:
SELECT *
FROM tPhones
WHERE dept = ?
AND (hid = ? OR (hid = 1 AND
NOT EXISTS (SELECT 1
FROM tPhones
WHERE dept = ?
AND hid = ?)))
ORDER BY location
I am using linq to Entity to retrieve data from to different tables by joining them, but I also want to group them by the field problemDesc in order to get rid of unnecessary duplicate entries for the same problem.
here is the code:
using (AssistantEntities context = new AssistantEntities())
{
var problems = context.tblProblems;
var customers = context.tblCustomers;
var query =
from problem in problems
join customer in customers
on problem.CustID equals customer.custID
where problem.IsActive == true
orderby customer.isMonthlyService == true descending
select new
{
problemID = problem.problemID,
ProblemCreateDate = problem.ProblemCreateDate,
CustID = problem.CustID,
name = customer.name,
isMonthlyService = customer.isMonthlyService,
StationName = problem.StationName,
problemDesc = problem.problemDesc,
LogMeIn = problem.LogMeIn
};
return query.ToList();
}
I am doing query.toList() in order to use that list in a gridview as a dataSource.
and if it possible, also add a field that count the duplicate problems.
You have plenty of examples in the following link.
LINQ - Grouping Operators
Got 2 tables: db.Tags (ID, TagName) and db.Names (ID, Name, TagID).
I want to fetch all db.Tags rows, and all the Names matching the TagID.
So it will look like
ID - TagName - Names
1 - tag1 - name1, name2, name3
2 - tag2 - name4, name5, name6
Is this possible in one (long) linq query?
or do I have to get all the tags, then do foreach tag, get all the names, then do foreach names to put them in a one long string..
Thanks in advance!
EDIT:
Okay see my comment on the second answer (first one up..), this is what i tried but i get some errors in compiler:
var tags =
from t in db.Tags
orderby t.Priority ascending
select new {
t.ID,
t.Name,
t.Priority,
Places = String.Join(", ",
(from p in db.Places
join o in db.TagToPlaces on new {
p.ID,
t.ID
}
equals new {
o.PlaceId,
o.TagId
}
select p.Name
).ToArray()
)
}
);
I think this is what you're after:
var query =
from t in db.Tags
select new
{
t.ID,
t.TagName,
Names = String.Join(", ",
(from n in db.Names
where n.TagID == t.ID
select n.Name)
.ToArray()),
};
With this I get the same sort of output that you gave in your question. I also understood that you want to output the tag id and name even when there are no associated name records - my query does that.
Now depending on if you're using EF or LINQ-to-SQL or something else you may need to add .ToArray() to the db.Tags & db.Names references to force the database query to occur.
If you have a large number of tag records you'll find you have a large number of queries going to the database. You could make this change to reduce it to only two queries:
var tags = db.Tags.ToArray();
var names = db.Names.ToArray();
var query =
from t in tags
select new
{
t.ID,
t.TagName,
Names = String.Join(", ",
(from n in names
where n.TagID == t.ID
select n.Name)
.ToArray()),
};
Now you just need to make sure that your data fits into memory - but it sounds like it should. I hope this helps.
Since the concat is a pain in TSQL, I would query the 3 values "as is", and format from there:
var list = (from tag in db.Tags
join name in db.Names
on tag.ID equals name.TagId
orderby tag.ID
select new { tag.ID, tag.TagName, name.Name }).ToList();
for example, if I wanted the names by tag-id, I could do:
var namesByTag = list.ToLookup(row => row.ID, row => row.Name);
(or whatever else you choose)