Error on using GroupBy in Linq - c#

~ error says image seen below i don't know why is it? is there another way to pick up the data without the error? i'm using distinct or group by.
var query = (from i in SFC.TransacRRrecords where i.POPRCTNM == p
group i by new {
i.VendorID,
i.VENDNAME,
i.SUBTOTAL,
i.PymtrMID,
i.TRUCKNO,
i.REMARKS,
i.VPNum,
i.VPDate,
i.AmountInWords
} into grp
select new
{
Vcode = grp.Key.VendorID,
Vdesc = grp.Key.VENDNAME,
Vsubtotal = grp.Key.SUBTOTAL,
Vterms = grp.Key.PymtrMID,
Vtruckno = grp.Key.TRUCKNO,
Vremarks = grp.Key.REMARKS,
Vvpno = grp.Key.VPNum,
Vvpdate = grp.Key.VPDate,
Vamntword = grp.Key.AmountInWords
}).FirstOrDefault();
ListViewItem List = new ListViewItem(query.Vcode);
List.SubItems.Add(query.Vdesc);
List.SubItems.Add(string.Format("{0:n2}", query.Vsubtotal));
List.SubItems.Add(query.Vterms);
List.SubItems.Add(query.Vtruckno);
List.SubItems.Add(query.Vremarks);
List.SubItems.Add(query.Vvpno);
List.SubItems.Add(query.Vvpdate);
List.SubItems.Add(query.Vamntword);
deletedRRHeaderList.Items.AddRange(new ListViewItem[] { List });

Related

order two list join and return ordered by date c# with linq

I need an help here! I always get an error from linq (wrong expression). Should work but it´s not... I don´t get any error when order by max Id but I need to get the Id of the max date group by IDFiscal and CodigoXPCliente. I tried diferent ways but I always get an error.
var queryTemp =
(from u in _userManager.Users.Where(u => u.TipoUsuario == "Cliente")
join ass in context.AssessoresCliente on u.Id equals ass.ApplicationUser.Id into temp_ass
from temp in temp_ass
select new ListaBaseCliente_Atendimento
{
Nome = u.Nome,
IDFiscal = u.IDFiscal,
Email = u.Email,
PhoneNumber = u.PhoneNumber,
DataPessoa = u.DataPessoa,
DataCadastro = temp.DataCadastro,
CodigoXPCliente = temp.CodigoXPCliente,
AssessorCambio = temp.AssessorCambio,
AssessorProtect = temp.AssessorProtect,
CodigoAssessorXP = temp.CodigoAssessorXP,
ClienteCambio = temp.ClienteCambio,
ClienteProtect = temp.ClienteProtect,
ClienteXP = temp.ClienteXP,
AssessorXP = temp.AssessorXP,
CadastroValido = true,
DataRegistroUsuario = temp.DataRegistroUsuario,
DataArquivo = DataHoje,
ContaXPNova = temp.ContaXPNova,
ImportacaoBitrix = temp.ImportacaoBitrix,
IdAssessoresCliente = temp.Id,
RegistroValido = temp.RegistroValido
}).AsEnumerable();
var agrup = from s in queryTemp group s by new { s.IDFiscal, s.CodigoXPCliente } into g
select g.OrderByDescending(t => t.DataRegistroUsuario).FirstOrDefault();

How to return list of object which associated with one ID?

I am still getting familiar with SQL and LINQ and I am trying to get every objects and its objects which is under one ID.
The below is the EDMX Diagram.
I am passing ClientID and I want to list everything that is under that ClientID and the below is my query to do so but as you can see query is only returning the first element but how to change it to return the list of every elements as below:
Passed ClientID
THeaderTitle 1
TReportName 1
TReportName 2
MY query is below which is returning the first element:
public TReportHeaderModel GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
}).First();
return query;
}
}
I've got it working!
I had to change it in my interface as
IList GetHeadersByClient (int ClientID);
So that I can return List of elements in my controller to pass to view.
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
});
return query.ToList();
}
}

StringBuilder within IEnumerable

I have a ControlMeasure table that holds information on each control measure and a ControlMeasurepeopleExposed Table that holds a record for each person exposed in the control measure this could be 1 record or many records.
I Have a controller that populates a List view
For each item in the list, Control Measure, I would like to create a string that shows all the People at risk
e.g.
PeopleString = "Employees, Public, Others";
Ive added a foreach in the controller to show what I'm trying to do however I'm aware that this wont work.
The controller is this:
public ActionResult ControlMeasureList(int raId)
{
//Populate the list
var hazards = new List<Hazard>(db.Hazards);
var controlMeasures = new List<ControlMeasure>(db.ControlMeasures).Where(x => x.RiskAssessmentId == raId);
var cmcombined = (
from g in hazards
join f in controlMeasures
on new { g.HazardId } equals new { f.HazardId }
select new CMCombined
{
Activity = f.Activity,
ControlMeasureId = f.ControlMeasureId,
ExistingMeasure = f.ExistingMeasure,
HazardName = g.Name,
LikelihoodId = f.LikelihoodId,
Rating = f.Rating,
RiskAssessmentId = f.RiskAssessmentId,
SeverityId = f.SeverityId,
}).OrderBy(x => x.Activity).ToList();
var cmPeopleExp = new List<ControlMeasurePeopleExposed>(db.ControlMeasurePeopleExposeds).Where(x => x.RiskAssessmentId == raId);
var peopleExp = from c in cmPeopleExp
join d in db.PeopleExposeds
on c.PeopleExposedId equals d.PeopleExposedId
orderby d.Name
select new RAPeopleExp
{
RAPeopleExpId = c.PeopleExposedId,
PeopleExpId = c.PeopleExposedId,
PeopleExpName = d.Name,
RiskAssessmentId = c.RiskAssessmentId,
ControlMeasureId = c.ControlMeasureId
};
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
ControlMeasureId = t.ControlMeasureId,
HazardName = t.HazardName,
LikelihoodId = t.LikelihoodId,
Rating = t.Rating,
SeverityId = t.SeverityId,
Activity = t.Activity,
ExCM = t.ExistingMeasure,
//This section here is where I'm struggling
var PeopleString = new StringBuilder();
foreach (var p in peopleExp)
{
PeopleString.AppendLine(p.PeopleName);
{
PeopleExposed = PeopleString,
});
return PartialView("_ControlMeasureList", model);
}
I know I cant directly put this code in the controller but it does represent what I want to do.
You can't foreach within an object initializer (which is what you're trying to do when instantiating FullControlMeasureListViewModel). You can, however, use a combination of string.Join and peopleExp.Select:
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
//other props
PeopleExposed = string.Join(",", peopleExp
.Where(p => p.ControlMeasureId == t.ControlMeasureId)
.Select(p => p.PeopleExpName));
//other props
});

LINQ result to object initializer

I have a problem with converting linq result to object.
I have a class called Plant and a database which contains information about it (for example name, latin name, habitats etc).
I want to create a new object from executed query and send it to another part of application. So I'm messing with this code:
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var sPlant = (from p in dc.Plants where p.Name == plantName select new Plant
{
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}
);
But it doesn't convert result to a new Plant object.
As it seems that Plant is not part of the data store, you need to return an object that Linq to SQL can handle, to then create your Plant instance locally.
Start by querying for a list of anonymous objects containing the properties you need, and then only create your Plant. Add a First() or a FirstOrDefault() at the end to retrieve only one Plant:
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var sPlant = (from p in dc.Plants where p.Name == plantName
select new {
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}).AsEnumerable().Select(p => new Plant
{
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}).First();
}
Use First or FirstOrDefault function to get the object. See here to get the difference.
If your query is suppose to return multiple results, use .TOList(). If you want to take first row only,use FirstOrDefault()

Is there a way to combine 2 LINQ2XML queries?

var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements()
}).SingleOrDefault();
var fields = from item in instructions.fields
select new
{
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};
I think something like this should work. I added the Select method to return the anonymous class.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements().Select(item => new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
}
).SingleOrDefault();
If you don't want to use the Select Extension method, you can use LINQ syntax. Here is an example of this.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = from e in item.Element("fields").Elements()
select new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
} // End of inner select statement
} // End of outer select statement
).SingleOrDefault();

Categories

Resources