Add list to a list - c#

I have the following code:
var columnNames = (from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select GetDbColumnNames(autoExport.AutoExportTemplate, realName)).ToList();
Where the function GetDbColumns() returns an List<string>.
So columNames is of the type List<List<string>>.
Is it possible to create a List<string>, so each element of the list of GetDbColumns is added to the result of the LinQ query?

You can use the "select many" construction:
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
from column in GetDbColumnNames(autoExport.AutoExportTemplate, realName)
select column).ToList();
Or here is an alternative way of using SelectMany:
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select autoExport
).SelectMany(x => x.GetDbColumnNames(autoExport.AutoExportTemplate, realName))
.ToList();
And finally, this is another way to put it (but it includes the somewhat ugly code x => x):
var columnNames = (
from autoExport in dataContext.AutoExports
where autoExport.AutoExportTemplate != null
&& ContainsColumn(autoExport.AutoExportTemplate, realName)
select autoExport.GetDbColumnNames(autoExport.AutoExportTemplate, realName)
).SelectMany(x => x).ToList();

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

i am trying to write a search query based upon different keys where keys can be null

i am trying to write search query in linq based upon attributes of an object where object attributes can be null.
i want to filter result if my column matches the value of some attribute. i.e object.country == "pakistan" then all the records of country pakistan should be displayed and if object.country is NULL then all records should be selected.
var query = from x in db.user_info
join y in db.user_detail_info on x.Id equals y.Id
where (key != null && key >= x.country) || (key == null)
select x;
What you are trying to do is essentially a left join, linq does not support left joins unfortunately. But there is a way around this.
Your linq becomes this...
var q =
from x in db.user_info
join y in db.user_detail_info on x.Id equals y.Id
where (key == null) || (x.country == key)
select x;
I believe you want something like this?
PS - Unable to test it right now.
string country = null; // set this var to a country name
var peopleList = model.People
.Join(model.PeopleDetails,
p => p.PeopleID,
pd => pd.PeopleID,
(p, pd) => new { p, pd })
.Where(resultSet =>
string.IsNullOrWhiteSpace(country)
? true
: resultSet.pd.CountryName.Equals(country))
.Select(resultSet => resultSet.p)
.ToList();

Trying to order LINQ results

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)

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