I have 2 lists
var listquestionold = db.tblExamQuetions.Where(p => p.QuetionExamId == oldexamid).ToList();
var listquestionnew = listquestionnew = db.tblExamQuetions.Where(p => p.QuetionExamId == examid ).ToList();
List<tblExamQuestionAnswers> listanswers = new List<tblExamQuestionAnswers>();
How can I get answers where questionId is in listquestionold:
listanswers =db.tblanswers.where(p=> p.ExamQuestionId exists in listquestionold ?
It's easy with Contains method of the List:
var listquestionold = db.tblExamQuetions.Where(p => p.QuetionExamId == oldexamid).ToList();
var listanswers = db.tblanswers.Where(w => listquestionold.Contains(w.ExamQuestionId)).ToList();
Related
When I run the following Linq:
var selectedProduct = db.Products.FirstOrDefault(a => a.ProductNr == productNr)?.Id;
model.PackTypes = db.Zones
.Where(az => az.ProductId == selectedProduct && az.StoragePrio > 0)
.ToList()
.DistinctBy(p => p.PackType)
.OrderBy(x => x.PackType)
.Select(x => new DropdownItemViewModel<int>
{
Id = (int)x.PackType,
Name = x.PackType.Translate()
});
return true;
I get this error:
System.InvalidOperationException: 'Nullable object must have a value.' on this code Id = (int)x.PackType,
Now I know I must do a nullcheck so I have tried this:
if (x.PackType != null)
return new DropdownItemViewModel<int>
{
Id = (int)x.PackType,
Name = x.PackType.Translate()
};
return null;
Still doesn't work, by that I mean I still have problem with NullCheck.
This query more effective and should not have all mentioned errors:
var query =
from p in db.Products
where p.ProductNr == productNr
join az in db.Zones on p.Id equals az.ProductId
where az.StoragePrio > 0 && az.PackType != null
select new { az.PackType };
model.PackTypes = query
.Distinct()
.OrderBy(x => x.PackType)
.Select(x => new DropdownItemViewModel<int>
{
Id = (int)x.PackType,
Name = x.PackType.Translate()
})
.ToList();
Instead of two database requests this query sends only one. Also all operations are done on the server side.
New to C# and appreciate any help. The issue is that I need to filter the results of my api call against an array (using an "allowedA" and "allowedB" array.) I don't know how to edit the lambda expression to check against the loop.
var activities = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY);
var activityTypes = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY_TYPES);
var documentEventxx = activities.Select(type => type.Id);
long [] allowedA = new long []{ 7137, 40385637};
long [] allowedB = new long []{ 7137, 40385637};
foreach (long value in documentEventxx)
{
foreach (var item in allowed)
{
if (item == value) {
//These are the values I am looking for -> values that are part of the documentEventxx and allowedB.
}
}
}
var result = activityTypes.Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
I have been reading about lambda expressions and foreach loops so please don't just post a random link.
Thanks in advance.
Filter the values before Selecting.
activityTypes.Where(x=>allowedA.Contains(x.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id && allowedB.Contains(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id,
Text = t.Name
}).ToList()
})
To filter you use .Where. You .Select to create a list of new types. So in order to filter, then create the lists of objects you want:
var result = activityTypes.Where(type=>isAllowed(type.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id&&isAllowed(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
I hope you can help me with this.
I want to convert this query from SQL in a lambda expression in C#:
select
a.Descripcion
from
pb.MantenimientosTipos a
where
a.activo = 1 and
a.idSegmento in (select b.idSegmento
from pb.MaquinasRelSegm b
where b.idMaquina = 67)
How can I do this?
I have two selectList, "a" and "b", the selectList "a" is list from table b filter by a parameter and the selectList "b" is a list from table a filter by SelectList "a"
private SelectList a (bool agregarTodo = false)
{
var segmentos = pb.MaquinasRelSegm.Where(x => x.idMaquina == MaquinaId).Select(x => x.Segmentos).ToList();
if (agregarTodo)
{
segmentos.Add(new PB.Domain.Entities.Segmentos { idSegmento = 0, Descripcion = "Todos" });
}
return new SelectList(segmentos, "idSegmento", "Descripcion");
}
private SelectList b (byte idSegmento, bool agregarTodo = false)
{
var tipos = pb.MantenimientosTipos.Where(x => x.idSegmento == idSegmento && x.Activo).ToList();
if (agregarTodo)
{
tipos.Insert(0, new PB.Domain.Entities.MantenimientosTipos { idTipoMTTO = 0, Descripcion = "Todo" });
}
return new SelectList(tipos, "idTipoMTTO", "Descripcion")
}
I want to put only one selectList with this SQL query
This is the relationship in SQL SERVER
https://drive.google.com/file/d/0BzpCEYwGGpogRGRaOVNXTDBrTWc/view?usp=sharing
Thanks for the diagram.
try to use this (assuming that pb is the EF context):
var segmentoIds = pb.MaquinasRelSegm
.Where(a => a.idMaquina == 67)
.Select(a => a.idSegmento)
.ToList();
var description = pb.MantenimientosTipos
.Where(a => a.Activo && segmentoIds.Contains(a.idSegmento))
.Select(a => a.Description);
I need to return two fields using a lambda expression. The first one is the sum of the amount field and the second one is CurrentFinancial year. Below is the code that I have written, how do I include CurrentFinancialYear?
var amount = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId)
.Sum(o => o.Amount);
return new Contribution { Amount = amount ?? 0, CurrentFinancialYear = };
Grouping by Year should do the trick:
from entry in ledger.Entries
where entry.ContactID == contactId
&& entry.Time.Year == currentFinancialYear
group entry by entry.Time.Year
into g
select new Contribution ()
{
Amount = g.ToList ().Sum (e => e.Amount),
CurrentFinancialYear = g.Key
};
UPDATE - just return the first/default result...
(from entry in ledger.Entries
where entry.ContactID == contactId
&& entry.Time.Year == currentFinancialYear
group entry by entry.Time.Year
into g
select new Contribution ()
{
Amount = g.ToList ().Sum (e => e.Amount),
CurrentFinancialYear = g.Key
}).FirstOrDefault();
First of all use a simple select
var contribution = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId).ToList();
It will give you a list of type vw_GetContribution
Then use groupby on this list as
var groupedContribution = contribution.GroupBy(b => b.CurrentFinancialYear).ToList();
Now you can iterate through or use this list as
foreach(var obj in groupedContribution.SelectMany(result => result).ToList())
{
var amount = obj.Amount;
var Year = obj.CurrentFinancialYear;
}
OR
In single line, you can do all the above as
var contList = context.vw_GetContribution
.Select(a => new { a.Amount, a.CurrentFinancialYear })
.GroupBy(b => b.CurrentFinancialYear)
.SelectMany(result => result).ToList();
I hope this will solve your problem.
Can you try this:
var amount = dealingContext.vw_GetContribution
.Where(o => o.ContactID == contactId)
.GroupBy(o=> new { o.CurrentFinancialYear, o.Amount})
.Select(group =>
new {
year= group.Key.CurrentFinancialYear,
sum= group.Sum(x=>x.Amount)
});
I want to use this query:
var queryData = from va in xdoc.Descendants("language")
select new
{
StringID = va.Parent.Parent.Attribute("id").Value,
Language = va.Attribute("name").Value,
LanguageData = va.Element("value").Value,
};
var organizedData = from x in queryData
group x by x.StringID into xg
select new
{
StringID = xg.Key,
English = xg.SingleOrDefault(x => x.Language == "ENGLISH_US").LanguageData,
Custom = xg.SingleOrDefault(x => x.Language == languageBox.SelectedItem.ToString()).LanguageData,
};
mainView.DataSource = organizedData.ToList();
mainView.Refresh();
except that as an additional condition for what is retrieved for the Custom anonymous type, its value must be equal to "*".
Why can't I figure this out? I guess I don't know enough about anonymous types or the => operator.
Is that what you want?
mainView.DataSource = organizedData.Where(x => x.Custom == "*").ToList();
I think this is what you're looking for. I put the value in a temp variable so it doesn't have to be computed twice.
var organizedData = from x in queryData
group x by x.StringID into xg
let temp = xg.SingleOrDefault(x => x.Language == languageBox.SelectedItem.ToString()).LanguageData
where temp == "*"
select new
{
StringID = xg.Key,
English = xg.SingleOrDefault(x => x.Language == "ENGLISH_US").LanguageData,
Custom = temp,
};