Trying to order LINQ results - c#

To one of my tables I added a sortOrder. I now need to update this query to respect the sortOrder authority!
Here is my current query:
var HTMLdocs = db.ProcedureDocs.Where(m => m.Procedures.Processes.processID == id && m.Document.html != null && m.Document.approvedBy != null).Select(m => m.Document);
The table that has sortOrder is Procedures.
How can I get the above query to return results that are ordered by sortOrder.
Here is the table structure.
Processes can have 0 or many Procedures.
Document can have 0 or many ProcedureDocs.
ProcedureDocs has a foreign key to Procedures on procedureid.
I somehow need to grab a collection of Document that somehow respects the order found in the Procedures table.
Let me know if you need any other information.

Try something like this:
var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null)
.OrderBy(m => m.Procedures.sortOrder)
.Select(m => m.Document);
Or in query syntax:
var HTMLdocs =
from m in db.ProcedureDocs
where m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null
orderby m.Procedures.sortOrder
select m.Document;

var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id
&& m.Document.html != null && m.Document.approvedBy != null)
.OrderBy(x=>x.Procedures.sortOrder)
.Select(m => m.Document)

Related

Loop a query match and remove subset items

I have the following two tables which hold the information on items that have been completed I needed to do it this way for reporting purposes.
qry = db.AssemblyListItems
.AsNoTracking()
.Where(x => x.ProductionPlanID == (long)_currentPlan.ProductionPlan )
.ToList();
var _query = qry.Where(w => w.ItemCode == "EPR15CT.L01" && w.DocumentNo == "0000026590")
.SingleOrDefault();
var hasbeenAssembled = dbCompletedPrinteds
.AsNoTracking()
.Where(x => x.ProductionPlanId == (long)_currentPlan.ProductionPlan)
.ToList();
foreach (var item in hasbeenAssembled) {
qry.RemoveAll(X => X.SOPOrderReturnID == Int32.Parse(item.SopLineItemId) );
}
If it finds any matching items in the second table to remove it from the main query.
You will see the tables have much the same data stored in them. But for some reason the the items is still showing in the I need some way of looping the first query with the second query and removing the matching items from the qry object.
So steps I need to do is :
Loop completed and printed object remove any matching products with the same document number and item code and match the productplan id item and then remove it from the master AssemblyListItems query and then dispaly in a gui at the min its keeping the item in the list.
Edit 2
This would work but I dont think its very effiecent.
List<AssemblyListItems> _query = qry.ToList();
foreach (AssemblyListItems item in _query)
{
var hasbeenAssembled = db.CompletedPrinteds.AsNoTracking().Where(x => x.ProductionPlanId == item.ProductionPlanID).ToList();
foreach(var subitem in hasbeenAssembled )
{
if(item.ProductionPlanID ==subitem.ProductionPlanId && item.DocumentNo == subitem.DocumentNo && item.DocumentNo == subitem.DocumentNo)
{
qry.RemoveAll(x => x.ProductionPlanID == subitem.ProductionPlanId && x.DocumentNo == item.DocumentNo && x.ItemCode == subitem.StockCode);
}
}
}
Edit 3
To Show the items in the edmx
Last week I did query below using Left outer Join to get three group of data
var results = (from srs in srsEmps
join dest in destEmps on srs.EmpCode equals dest.EmpCode into dsNull
from dest in dsNull.DefaultIfEmpty()
select new { srs = srs, dest = dest }).ToList();
var Common = results.Where(x => (x.srs != null) && ( x.dest != null)).ToList();
var Deleted = results.Where(x => x.dest != null).ToList();
var NewlyAdded = results.Where(x => x.srs != null);
Something like this maybe?
//first get list of assembled/completed items with the _currentplan's ID:
var hasbeenAssembled =
dbCompletedPrinteds
.AsNoTracking()
.Where(x => x.ProductionPlanId == (long)_currentPlan.ProductionPlan)
//note: not sure of underlying DB technology here, but this .ToList() will
//typically cause a DB query to execute here.
.ToList();
//next, use that to filter the main query.
qry = db.AssemblyListItems
.AsNoTracking()
.Where(x =>
//Get current plan items
(x.ProductionPlanID == (long)_currentPlan.ProductionPlan)
//filter out items which are in the previous list of 'completed' ones
&& (!hasBeenAssembled.Any(hba => hba.SopLineItemId==x.SOPOrderReturnID))
)
.ToList();
//I don't have any idea what _query is for, it doesn't seem to be used for anything
//in this example...
var _query = qry.Where(w => w.ItemCode == "EPR15CT.L01" && w.DocumentNo == "0000026590")
.SingleOrDefault();

Joining table to a list using Entity Framework

I have the following Entity Framework function that it joining a table to a list. Each item in serviceSuburbList contains two ints, ServiceId and SuburbId.
public List<SearchResults> GetSearchResultsList(List<ServiceSuburbPair> serviceSuburbList)
{
var srtList = new List<SearchResults>();
srtList = DataContext.Set<SearchResults>()
.AsEnumerable()
.Where(x => serviceSuburbList.Any(m => m.ServiceId == x.ServiceId &&
m.SuburbId == x.SuburbId))
.ToList();
return srtList;
}
Obviously that AsEnumerable is killing my performance. I'm unsure of another way to do this. Basically, I have my SearchResults table and I want to find records that match serviceSuburbList.
If serviceSuburbList's length is not big, you can make several Unions:
var table = DataContext.Set<SearchResults>();
IQuerable<SearchResults> query = null;
foreach(var y in serviceSuburbList)
{
var temp = table.Where(x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId);
query = query == null ? temp : query.Union(temp);
}
var srtList = query.ToList();
Another solution - to use Z.EntityFramework.Plus.EF6 library:
var srtList = serviceSuburbList.Select(y =>
ctx.Customer.DeferredFirstOrDefault(
x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId
).FutureValue()
).ToList().Select(x => x.Value).Where(x => x != null).ToList();
//all queries together as a batch will be sent to database
//when first time .Value property will be requested

Simplify LINQ query

I have the following query:
db.ObjectTags.Where(c =>
c.TagID == tagID &&
(!db.DeletedObjects.Any(d=> d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID)
|| !db.DeletedObjects.SingleOrDefault(d => d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID).Deleted)
)
Its goal is to return objects that are not in a deleted state.
The table DeletedObjects has two states:
A record doesn't exist (not deleted)
A record exists with a deleted (bool) value
I need to query where either the record doesn't exist, or if it does the deleted value is false.
Is there any way to condense that statement eg with SingleOrDefault()?
You only need one !db.DeletedObjects.Any(...) and no SingleOrDefault
var q = db.ObjectTags
.Where(c=> c.TagID == tagID && !db.DeletedObjects
.Any(d => d.Deleted && d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID));
Can you please try this linq query
db.ObjectTags.Where(c =>
c.TagID == tagID &&
(db.DeletedObjects.Any(d=> d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID && !c.Deleted))
)
I believe you need to left join between ObjectTags and DeletedObjects. A LINQ query like this:
from objectTag in db.ObjectTags
from deletedObject in db.DeletedObjects
.Where(deletedObject => deletedObject.ForObjectTypeID == objectTag.ForObjectTypeID && deletedObject.ForObjectID == objectTag.ForObjectID)
.DefaultIfEmpty()
where deletedObject == null || !deletedObject.Deleted

filtering results with Entity Framework

another kinda newbie question I guess. I have EF setup and now I want to select some records based on a filter. I have SomeClass with 4 items (all strings to keep things simple, lets call them string1, string2, and so on). Now, in a post I send the filter in an instance of SomeClass, but maybe not all properties are filled in.
So you might end up with string1="something", string2="bla" and string4="bla2". So string 3 = null. Now, how do I setup the query? If i try something like:
var dataset = entities.mydatabase
.Where(x => x.string1 == someclass.string1 && x.string2 == someclass.string2 && x.string3 == someclass.string3 && x.string4 == someclass.string4)
.Select(x => new { x.string1, x.string2, x.string3, x.string4}).ToList();
... I get no results, because string3=null. I could do something with checking all parameters and see if they're set and create the query based on that, but there must be something more elegant than that.
Anyone?
Thanks!
Ronald
The following will return all rows where the someclass.string is null OR equals to x.string.
var dataset = entities.mydatabase
.Where(x => someclass.string1 == null || x.string1 == someclass.string1)
.Where(x => someclass.string2 == null || x.string2 == someclass.string2)
.Where(x => someclass.string3 == null || x.string3 == someclass.string3)
.Where(x => someclass.string4 == null || x.string4 == someclass.string4)
.Select(x => new { x.string1, x.string2, x.string3, x.string4}).ToList();

Linq query for distinct data from a table with where condition

I have an sql statement like this:
select distinct(agent_name)
from properties
where agent_name not in ('null','')
I want the linq query in C# page
Assuming you're comparing to the string value 'null' like your original query:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != "null" &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
If you're actually comparing to a null value just change it to:
List<string> agentNames = db.Properties.Where(p=>p.AgentName != null &&
p.AgentName != "")
.Select(p => p.AgentName)
.Distinct()
.ToList();
var result = context.Properties.Where(p => p.AgentName != null
&& p.AgentName != "")
.GroupBy(p => p.AgentName)
.Select(g => g.Key);
Try something like this
var result = (from dbo in database.Table
where dbo.agent_name!=null and dbo.agent_name !=''
select dbo.agent_name).Distinct();
or if you have a list already
var result = (list.Where(a => a.agent_name!=null && a.agent_name!='').Select(
a.agent_name)).Distinct();
You can use it like this
var forms = db.properties.
Where(a => a.agent_name == 'null' || a.agent_name == null).
Select(x => x.agent_name).
Distinct().
ToList();
Its equivalent SQL statement, which is designed by LINQ to SQL is
SELECT
[Distinct1].[agent_name] AS [agent_name]
FROM ( SELECT DISTINCT
[Extent1].[agent_name] AS [agent_name]
FROM [dbo].[properties] AS [Extent1]
WHERE [Extent1].[agent_name] = N'null' OR [Extent1].[agent_name] = N''
) AS [Distinct1]

Categories

Resources