LINQ in c#: Foreach inside linq - c#

I have trouble selecting rows in a dynamic way.
foreach (var item in _listBox.SelectedItems)
{
Treinen treinData = (Treinen)item;
Debug.WriteLine(treinData.Name);
}
Here i get the selected items name from a listbox with about 60 names in, depending on the selection I want to get the representing SQL data for those selected. I think this requires to append a dynamic .Where clause.
ObjectQuery<Fouten> fouten = eventsEntities.Foutens;
loadedData =
(from fout in fouten
where datumStart <= fout.Datum && datumEnd >= fout.Datum
.... here should where be extended in some way, for example:
&& foreach (var item in _listBox.SelectedItems)
{
Treinen treinData = (Treinen)item;
where fout.Treinen.Name == treinData.Name
}
orderby fout.Datum, fout.Time
select new
{
Datum = fout.Datum,
Time = fout.Time,
FoutCode = fout.FoutCode,
Omschrijving = fout.Omschrijving,
Teller = fout.Teller,
Module = fout.Module.ToUpper(),
FoutId = fout.FoutId,
TreinId = fout.TreinId
}).AsEnumerable().Select(x => new Fouten
{
Datum = x.Datum,
Time = x.Time,
FoutCode = x.FoutCode,
Omschrijving = x.Omschrijving,
Teller = x.Teller,
Module = x.Module,
FoutId = x.FoutId,
TreinId = x.TreinId
})
.ToList();
Obviously that doesn't work but hopefully it makes sense to what I'm trying to accomplish. Right now I get the data for all items instead of the selected ones. Anyone has a idea on how to solve?

I suppose your "Treinen" has an ID-Field (or Property) in it and since you have your fout.TreinId it is easier to go for the ID.
you can fill your ID-list before going into the query and then just check if your ID is in the List:
List<int> treinenIds = new List<int>();
foreach (var item in _listBox.SelectedItems)
treinenIds.Add(((Treinen)item).Id);
ObjectQuery<Fouten> fouten = eventsEntities.Foutens;
loadedData =
(from fout in fouten
where datumStart <= fout.Datum && datumEnd >= fout.Datum
//where-clause
where treinenIds.Contains(fout.TreinId)
orderby fout.Datum, fout.Time
select new
{
Datum = fout.Datum,
Time = fout.Time,
FoutCode = fout.FoutCode,
Omschrijving = fout.Omschrijving,
Teller = fout.Teller,
Module = fout.Module.ToUpper(),
FoutId = fout.FoutId,
TreinId = fout.TreinId
}).AsEnumerable().Select(x => new Fouten
{
Datum = x.Datum,
Time = x.Time,
FoutCode = x.FoutCode,
Omschrijving = x.Omschrijving,
Teller = x.Teller,
Module = x.Module,
FoutId = x.FoutId,
TreinId = x.TreinId
})
.ToList();
I'm not sure if the .Contains is supported in the query but if it is then this code should work for your Example.

Related

Why does my parallel.ForEach method return the wrong values?

I have a large List of objects (over 100k rows in a txt file). I have to do some data work with each item in the list I save the object to the database if it doesnt exist and if it does I increase a number column in the for the item and then update the database while saving the updated item.
If I use a regular foreach loop everything works out fine but it takes over 24 hours to finish.
The issue is that when I use a parallel loop the records do not match and sometimes I will get an error on the .Save() method that the item ID was changed.
THIS CODE WORKS
public List<SreckaIsplacena> UpisiUTabeleSerijski (List<SreckaTemp>srt)
{
_srecke = _glavniRepository.UcitajSamoaktivneSrecke().OrderByDescending(item => item.ID).ToList<Srecka>();
List<SreckaIsplacena> pomList = new List<SreckaIsplacena>();
SreckaIsplacena _isplacena;
foreach (SreckaTemp lt in srt)
{
string beznula = lt.sreIspBroj.TrimStart('0');
SreckeDobici srd = new SreckeDobici();
Srecka sr = (from s in _srecke
where s.Sifra == lt.sreSif && s.Serija == lt.sreSerija
select s).First();
List<SreckeDobici> srDob = _glavniRepository.DohvatiSreckeDobiciZaIsplatniBroj(sr, beznula);
if (srDob.Count == 1)
{
srd = srDob.ElementAt(0);
}
List<SreckaNagrade> sreckaNagrade = new List<SreckaNagrade>(_glavniRepository.DohvatiNagradeZaSrecku(sr.ID).OrderBy(item => item.SifraFox));
double iznos = lt.sreIznDob / lt.sreBrDob;
SreckaNagrade nag = (from sn in sreckaNagrade
where sn.Iznos == lt.sreIznDob
select sn).FirstOrDefault();
Odobrenje odo = new Odobrenje();
odo = odo.DohvatiOdobrenje(valutaGlavna.ID, lt.sreIsplatio).FirstOrDefault();
List<PorezSrecka> listaPoreza = _glavniRepository.UcitajPorezSrecka(valutaGlavna, odo, sr, nag.NagradaId);
List<SreckaIsplacena> sveIsplacene = _glavniRepository.DohvatiIsplaceneSreckeZaValutuIProdavacaSreckuNagraduNovo(valutaGlavna.ID, sr.ID, nag.NagradaId, lt.sreIsplatio);
if (sveIsplacene.Count > 1)
{
System.Windows.MessageBox.Show("Greska, ista srecka s istim dobitkom kod istog prodavaca u istoj valuti 2 put nadjena u bazi");
}
else if (sveIsplacene.Count == 1)
{
_isplacena = sveIsplacene.ElementAt(0);
_isplacena.BrojDobitaka = _isplacena.BrojDobitaka + lt.sreBrDob;
_isplacena.Update();
var index = pomList.FindIndex(r => r.ID == _isplacena.ID);
if (index != -1)
{
pomList[index] = _isplacena;
}
}
else if (sveIsplacene.Count==0)
{
_isplacena = new SreckaIsplacena();
decimal iz = Convert.ToDecimal(lt.sreIznDob);
_isplacena.BrojDobitaka = lt.sreBrDob;
_isplacena.Iznos = iz;
_isplacena.Nagrada = nag;
_isplacena.Prodavac = lt.sreIsplatio;
_isplacena.Valuta = valutaGlavna;
_isplacena.Srecka = sr;
_isplacena.Cijena = Convert.ToDecimal(sr.Cijena);
if (listaPoreza.Count == 1)
{
PorezSrecka ps = listaPoreza.ElementAt(0);
_isplacena.SreckaPorez = ps;
}
_isplacena.Save();
int ispID = _isplacena.ID;
if (ispID != 0)
{
srd.Sre_isplatio = lt.sreIsplatio;
srd.Sre_valuta = valutaGlavna;
srd.Update();
}
pomList.Add(_isplacena);
}
}
return pomList;
}
THIS CODE DOES NOT WORK
public List<SreckaIsplacena> UpisiSamoUTabele(ConcurrentBag<SreckaTemp> srt)
{
_srecke = _glavniRepository.UcitajSamoaktivneSrecke().OrderByDescending(item => item.ID).ToList<Srecka>();
List<SreckaIsplacena> pomList = new List<SreckaIsplacena>();
SreckaIsplacena _isplacena;
Parallel.ForEach(srt, (lt) =>
{
string beznula = lt.sreIspBroj.TrimStart('0');
SreckeDobici srd = new SreckeDobici();
Srecka sr = (from s in _srecke
where s.Sifra == lt.sreSif && s.Serija == lt.sreSerija
select s).First();
List<SreckeDobici> srDob = _glavniRepository.DohvatiSreckeDobiciZaIsplatniBroj(sr, beznula);
if (srDob.Count == 1)
{
srd = srDob.ElementAt(0);
}
List<SreckaNagrade> sreckaNagrade = new List<SreckaNagrade>(_glavniRepository.DohvatiNagradeZaSrecku(sr.ID).OrderBy(item => item.SifraFox));
SreckaNagrade nag = (from sn in sreckaNagrade
where sn.Iznos == lt.sreIznDob
select sn).FirstOrDefault();
Odobrenje odo = new Odobrenje();
odo = odo.DohvatiOdobrenje(valutaGlavna.ID, lt.sreIsplatio).FirstOrDefault();
List<PorezSrecka> listaPoreza = _glavniRepository.UcitajPorezSrecka(valutaGlavna, odo, sr, nag.NagradaId);
List<SreckaIsplacena> sveIsplacene = _glavniRepository.DohvatiIsplaceneSreckeZaValutuIProdavacaSreckuNagraduNovo(valutaGlavna.ID, sr.ID, nag.NagradaId, lt.sreIsplatio);
if (sveIsplacene.Count == 1)
{
_isplacena = sveIsplacene.ElementAt(0);
lock (_isplacena)
{
_isplacena.BrojDobitaka = _isplacena.BrojDobitaka + lt.sreBrDob;
_isplacena.Update();
var index = pomList.FindIndex(r => r.ID == _isplacena.ID);
if (index != -1)
{
pomList[index] = _isplacena;
}
}
}
else if (sveIsplacene.Count==0)
{
_isplacena = new SreckaIsplacena();
decimal iz = Convert.ToDecimal(lt.sreIznDob);
_isplacena.BrojDobitaka = lt.sreBrDob;
_isplacena.Iznos = iz;
_isplacena.Nagrada = nag;
_isplacena.Prodavac = lt.sreIsplatio;
_isplacena.Valuta = valutaGlavna;
_isplacena.Srecka = sr;
_isplacena.Cijena = Convert.ToDecimal(sr.Cijena);
lock(_isplacena)
{
if (listaPoreza.Count == 1)
{
PorezSrecka ps = listaPoreza.ElementAt(0);
_isplacena.SreckaPorez = ps;
}
_isplacena.Save();
int ispID = _isplacena.ID;
if (ispID != 0)
{
srd.Sre_isplatio = lt.sreIsplatio;
srd.Sre_valuta = valutaGlavna;
srd.Update();
}
pomList.Add(_isplacena);
}
}
});
return pomList;
}
I tried using ConcurrentBag instead of List but ran into an issue because ConcurrentBag does not have the FindIndex method (var index = pomList.FindIndex(r => r.ID == _isplacena.ID);). I know there is some way to take out the object and put back in but not sure how to do that and from what I read Lists should be ok if you use locking which I am.
Please help.

EF copying entities with Navigation properties

I have a requirement to copy objects along with its navigation properties and create new objects. Following is what I did:
// get parent location's work availability template
WorkAvailTemplate workAvailTemplate = locationsFromDb.Where(l => l.Location2 == null).SingleOrDefault().WorkAvailTemplates.First();
foreach (var loc in locationsToAddOrUpdate)
{
// add op-hours template only for the new locations (the ID sometimes can be -1
if (loc.LocationId < 1)
{
if (workAvailTemplate != null)
{
WorkAvailTemplate wt = new WorkAvailTemplate
{
Location = loc,
CreatedBy = this.CurrentUser.Id,
CreatedDate = DateTime.Now,
NumberOfRotations = workAvailTemplate.NumberOfRotations,
ActiveStatus = workAvailTemplate.ActiveStatus
};
ClientContext.WorkAvailTemplates.Add(wt);
var workAvailTemplateDays = workAvailTemplate.WorkAvailTemplateDays.ToList();
foreach (WorkAvailTemplateDay d in workAvailTemplateDays)
{
WorkAvailTemplateDay wd = new WorkAvailTemplateDay
{
WorkAvailTemplate = wt,
WeekNumber = d.WeekNumber,
DayNumber = d.DayNumber,
ChangedBy = this.CurrentUser.Id,
ChangedDate = DateTime.Now
};
ClientContext.WorkAvailTemplateDays.Add(wd);
foreach (var r in d.WorkAvailTemplateTimeRanges)
{
WorkAvailTemplateTimeRange wr = new WorkAvailTemplateTimeRange
{
WorkAvailTemplateDay = wd,
StartTime = r.StartTime,
EndTime = r.EndTime,
ChangedBy = this.CurrentUser.Id,
ChangedDate = DateTime.Now
};
ClientContext.WorkAvailTemplateTimeRanges.Add(wr);
}
}
}
}
}
I'm sure there's a better way to do this rather than creating new objects. Any thoughts?
Earlier, when I did this for a single Location object creation, i did as follow and it works fine.
WorkAvailTemplate workAvailTemplate = (from wat in ClientContext.WorkAvailTemplates
where wat.FkLocationId == newLocation.FkParentLocationId
select wat).SingleOrDefault();
if (workAvailTemplate != null)
{
workAvailTemplate.Location = newLocation;
ClientContext.WorkAvailTemplates.Add(workAvailTemplate);
var workAvailTemplateDays = from watd in ClientContext.WorkAvailTemplateDays
join wat in ClientContext.WorkAvailTemplates on watd.FkWorkAvailTemplateId equals wat.WorkAvailTemplateId
where wat.FkLocationId == newLocation.FkParentLocationId
select watd;
foreach (WorkAvailTemplateDay d in workAvailTemplateDays)
{
d.WorkAvailTemplate = workAvailTemplate;
var workAvailTimeRangePerDay = (from r in ClientContext.WorkAvailTemplateTimeRanges.AsEnumerable()
where r.FkWorkAvailTemplateDayId == d.WorkAvailTemplateDayId
select this.f(r, d, newLocation));
ClientContext.WorkAvailTemplateDays.Add(d);
ClientContext.WorkAvailTemplateTimeRanges.AddRange(workAvailTimeRangePerDay);
}
}
But when I did the same for mutiple objects in a loop, it only creates for the first Location object. I don't get any errors, but simply they don't get created for others.

Linq-OrderByDescending doesn't work for me-ASP.net MVC

I want to order my list by idEtatD but this attribute isn't my table primarykey or id it's a normal attribute migrated from another table,nut OrderBy or OrderByDescending didn't give me a result my list still not ordered by idEtatD.
public ActionResult ListeDemande( int? page)
{
traçabilitérepository=new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
select new
{
id_demande=d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(listdemandes.OrderByDescending(x => x.idEtatD).ToList().ToPagedList(pageNumber, pageSize));
}
Please I need your help and thank you.
You can order the items at the beginning, but you need to include it in the list:
traçabilitérepository = new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
orderby t.idEtatD descending
select new
{
id_demande = d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande,
idEtatD = XXXX
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});

Check for missing elements while using LINQ to XML

I am trying get data from the xml. Below is the code which
gets data from the XDocument and return list<t>.
However, p.Element("Sponsor") can sometimes be null. How can I check for the null values
var atClauseList = doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG).Select(p => new AtClause()
{
ClauseNumber = (string)p.Element("Number"),
Sponsors = p.Element("Sponsor").Elements(SPONSOR_TAG).Select(y => y.Value)
.ToList(),
Page = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Page").ElementValueNull(),
Line = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Line").ElementValueNull(),
LineText = p.Element("Sponsor").Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull(),
ItalicText = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Italic").ElementValueNull(),
ParaList = p.Element("Sponsor").Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}
).ToList()
}).ToList();
move your code out of an object initializer, and add some logic to it:
var atClauseList = new List<AtClause>();
foreach(var item in doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG))
{
var atClause = new AtClause();
atClause.ClauseNumber = (string)item.Element("Number");
var sponsor = item.Element("Sponsor");
if (sponsor != null)
{
atClause.Sponsors = sponsor.Elements(SPONSOR_TAG).Select(y => y.Value).ToList();
atClause.Page = sponsor.Element("aItem").Element("AmendText").Element("Page").ElementValueNull();
atClause.Line = sponsor.Element("aItem").Element("AmendText").Element("Line").ElementValueNull();
atClause.LineText = sponsor.Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull();
atClause.ItalicText = sponsor.Element("aItem").Element("AmendText").Element("Italic").ElementValueNull();
atClause.ParaList = sponsor.Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}).ToList();
atClauseList.Add(atClause);
}
You can use sequences rather than leaving the IEnumerable immediately:
var value = (string)p.Elements("Sponsor")
.Elements("aItem")
.Elements("AmendText")
.Elements("Page")
.SingleOrDefault()

linq join, group by to get count of child table

After getting my join to work I seem to have gotten stuck on the count bit.
What I am attempting below is get a count of documents printed based on the join below.
What would the code be to get the count per 'guardiandocsrequired'?
var guardianEntityType = new {EntityTypeFK = "GUARDIAN"};
return (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
If it helps, I have written the sql to produce exactly what I require as follows:
SELECT gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus,
COUNT(dpl.DocPrintedID) AS documentsPrinted
FROM dbo.GuardianDocsRequired gdr
LEFT OUTER JOIN dbo.DocumentPrintingLog dpl ON gdr.DocTypeFK = dpl.DocTypeFK
AND gdr.GuardianFK = dpl.EntityFK
AND dpl.EntityTypeFK = 'GUARDIAN'
WHERE gdr.GuardianFK = #entityPK
GROUP BY gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus
Do you mean sth like this?
var guardiandocsrequired = (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
int cnt = guardiandocsrequired.Count;
return guardiandocsrequired;

Categories

Resources