I think this is kind of a basic question but I'm getting confused. I have two objects, Orders and OrderTags. In the database, Orders has no relation to OrderTags, but OrderTags has a FK relation to Orders.
So I capture both objects in my context like so:
orders = context.Orders;
tags = context.OrderTags.Where(tag=> tag.ID = myID);
Now I want to reduce the orders list to only be equal to the orders that exist in my tags list. Here is my best pseudocode of what I want to do:
orders = orders.Where(every order id exists somewhere in the tags list of order ids)
For clarification, each Tag object has a TagID and an OrderID. So I only want the orders that correspond to the tags I have looked up. Can anyone assist me with the syntax so I can get what I'm looking for?
Using a LINQ query:
var results = (from o in context.Orders
join t in context.Tags on o.OrderId equals t.OrderId
where t.ID == myID
select o ).ToList();
Using LINQ query:
orders = orders.Where(order => tags.Contains(tag => tag.ID == order.OrderID)).ToList();
Using a LINQ query with lambda expressions:
orders.RemoveAll(x => !tags.ConvertAll(y => y.tagId).Contains(x.tagID));
Something like this should work.
orders = orders.Where(o=>tags.Contains(t=>o.ID == t.OrderID));
You could also just perform a join.
Related
from what I've read, I can use LINQ to first group, then order each Group by using "SelectMany", which is described here: How to group a IQueryable by property 1 but order by property 2?
But this doesn't work for IQueryable I guess.
We basically get a BusinessObject with an Main-Entity and an IEnumable of Entities, so I'd like to first order by the Main-Entity sequence, then by each Name of the Subentities.
So I guess my query would look like this in LINQ to objects:
var qry = GetQueryFromSomeWhere();
qry = qry.OrderBy(f => f.MainEntity.SequenceNumber)
.ThenBy(f => f.SubEntities.SelectMany(f => f.Name));
I could order this Names in the Query-Service, but it should be up the consumer to order the entities as he needs.
Is there a possibility to make this work kindahow without loading all Entities in the Memory?
If I'am correctly understanding you want to sort records inside each group by record Name. I think that you could accomplish this by ordering records before doing a group by, try this code:
var q = from m in MainEntities
join s in SubEntities on m.Id equals s.MainId
orderby m.SequenceNumber, s.Name
group new { m, s } by m into grp
orderby grp.Key.SequenceNumber
select grp;
I have a sql statement like this:
DECLARE #destinations table(destinationId int)
INSERT INTO #destinations
VALUES (414),(416)
SELECT *
FROM GroupOrder grp (NOLOCK)
JOIN DestinationGroupItem destItem (NOLOCK)
ON destItem.GroupOrderId = grp.GroupOrderId
JOIN #destinations dests
ON destItem.DestinationId = dests.destinationId
WHERE OrderId = 5662
I am using entity framework and I am having a hard time getting this query into Linq. (The only reason I wrote the query above was to help me conceptualize what I was looking for.)
I have an IQueryable of GroupOrder entities and a List of integers that are my destinations.
After looking at this I realize that I can probably just do two joins (like my SQL query) and get to what I want.
But it seems a bit odd to do that because a GroupOrder object already has a list of DestinationGroupItem objects on it.
I am a bit confused how to use the Navigation property on the GroupOrder when I have an IQueryable listing of GroupOrders.
Also, if possible, I would like to do this in one trip to the database. (I think I could do a few foreach loops to get this done, but it would not be as efficient as a single IQueryable run to the database.)
NOTE: I prefer fluent linq syntax over the query linq syntax. But beggars can't be choosers so I will take whatever I can get.
If you already have the DestinationGroupItem as a Navigation-property, then you already have your SQL-JOIN equivalent - example. Load the related entities with Include. Use List's Contains extension method to see if the desired DestinationId(s) is(are) hit:
var destinations = new List<int> { 414, 416 };
var query = from order in GroupOrder.Include(o => o.DestinationGroupItem) // this is the join via the navigation property
where order.OrderId == 5662 && destinations.Contain(order.DestinationGroupItem.DestinationId)
select order;
// OR
var query = dataContext.GroupOrder
.Include(o => o.DestinationGroupItem)
.Where(order => order.OrderId == 5662 && destinations.Contain(order.DestinationGroupItem.DestinationId));
I want to filter my LINQ query based on an included table but am having some trouble.
Here is the original statement, which works:
return
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries");
Now I'm trying to filter on Careers using projected filtering but am having trouble. It compiles but it leaves out the Titles and Salaries tables, which causes runtime errors, and I can't seem to add those tables back in:
var query1 = (
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
select new
{
c,
Careers = from Careers in c.Careers
where Careers.IsActive == true
select Careers
});
var query = query1.AsEnumerable().Select(m => m.c);
return query.AsQueryable();
How can I include the titles and salaries tables in the filtered query?
You can simplify your query considerably, which should resolve your issue. I'm assuming that you want all people with at least 1 active career:
var query =
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
where c.Careers.Any(c => c.IsActive);
return query;
I would try something like,
var query = from p in ObjectContext.People
join c in ObjectContext.Careers on p equals c.Person
where c.IsActive
select p;
I am learning about LINQ-to-SQL and everything was going well until something strange happened:
I tried to make an example of distinct, so, using the Northwind dabatase I wrote the following query:
var query =
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
};
If I print the SQL generated by LINQ-to-SQL for the query stored in query it looks like this:
SELECT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
ORDER BY [t0].[CustomerID]
So, as usual, the query brings all the CustomerID for each Order in the Orders table ordered alphabetically.
But! If I use the Distinct() method like this:
var query = (
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
}).Distinct();
The query brings the expected results of the Distinct clause, but the CustomerIDs are not ordered despite I wrote orderby o.CustomerID!
The SQL query for this second LINQ query is the following:
SELECT DISTINCT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
As we can see **the ORDER BY clause is missing. Why is that?
Why does the ORDER BY clause disappears when I use the Distinct() method?
From the Queryable.Distinct documentation;
The expected behavior is that it returns an unordered sequence of the unique items in source.
In other words, any order the existing IQueryable has is lost when you use Distinct() on it.
What you want is probably something more like this, an OrderBy() after the Distinct() is done;
var query = (from o in db.Orders
select new
{
o.CustomerID
}).Distinct().OrderBy(x => x.CustomerID);
Try rearranging the members to place the OrderBy after the Distinct. You'll have to revert to method chaining:
db.Orders.Select(o=>o.CustomerId).Distinct().OrderBy(id=>id);
This would be the more efficient way to set up the query in Enumerable Linq anyway, because the OrderBy would then operate only on the unique items and not on all of them. Also, according to MSDN, Enumerable.Distinct does not guarantee the return order of the elements anyway, so ordering before deduping is pointless.
Due to the use of distinct, the order of the returned list is not guaranteed. LinqToSql is smart enough to recognize this, therefor it ignores it.
If you place the order by AFTER your Distinct, everything will happen as you desire.
var query = (from o in db.Orders
select new
{
o.CustomerID
}).Distinct().OrderBy(o => o.CustomerID);
or
var query = db.Orders.Select(o => o.CustomerID).Distinct().OrderBy(o => o.CustomerID);
Please see this article for clarification:
http://programminglinq.com/blogs/marcorusso/archive/2008/07/20/use-of-distinct-and-orderby-in-linq.aspx
You can simulate ORDERBY and DISTINCT with this counstruction:
var distinctItems = employees.GroupBy(x => x.EmpID).OrderBy(x => x).Select(y => y.First());
I have two IEnumerables:
IEnumerable<ThisEmployee> thisEmployees;
IEnumerable<ThatEmployee> thatEmployees;
They are populated from 2 separate contexts. ThisEmployee and ThatEmployee are not matching types. They don't share anything similar apart from an EmployeeNumber property.
I want to get all ThatEmployee.Notes for any employee in thatEmployees that has a matching EmployeeNumber in thisEmployees.
I can't for the life of me work out how.
Your collections come from different contexts so get ids of employees first in linq-to-objects:
var ids = from e1 in thatEmployees
join e2 in thisEmployees on e1.EmployeeNumber equals e2.EmployeeNumber
select e1.Id;
Now use ids to get Notes from the database in single query
var notes = from n in context.Notes
where ids.Contains(n.Employee.Id)
select n;
Since its in two different contexts try using ToList to get all objects. Then using Linq to Objects u can use Where(r => thisEmployees.Any(s => s.EmployeeNumber == r.EmployeeNumber)). Not sure if i understood u correctly :)
How about something like:
var notes = thatEmployees
.Join(thisEmployees,
ta => ta.EmployeeNumber,
ti => ti.EmployeeNumber,
(ta, ti) => ta.Notes)