how can i use dynamic columns instead of this query
id = row.Field<int>("id") ,
rec_date = row.Field<string>("rec_date")
var result = from row in dt.AsEnumerable()
group row by new
{
id = row.Field<int>("id") ,
rec_date = row.Field<string>("rec_date")
} into section1
select new
{
section1.Key.id,
section1.Key.rec_date,
children = from l2 in section1
select new
{
tax_rate = l2.Field<string>("tax_rate"),
tax_amount = l2.Field<string>("tax_amount")
}
};
var jsonString = JsonConvert.SerializeObject(result);
Related
I want to retrieve data from Project.Models.transaction_details by using linq, comparing value from list of string (List).
here is my code
List<transaction_details> transactions = new List<transaction_details>();
List<string> date_list = new List<string>();
// date_list output is ["2020-01-01","2020-01-02",2020-01-03",...,"2020-01-31"]
while (sdr.Read())
{
transactions.Add(new transaction_details
{
ID = sdr.GetInt32("ID"),
Transdate = sdr.GetDateTime("Transdate"),
Debit = sdr.GetDecimal("Debit"),
TransactionName =sdr.GetString("TransactionName"),
BranchID = sdr.GetString("BranchID")
});
}
var array1Index = date_list.Select((i, index) => new { Index = index, i = i }).ToList();
List<transaction_details> arrayresult = new List<transaction_details>();
var query1 = from a in array1Index
select transactions.Contains(a.i) == true ? a.i : "";
arrayresult = query1.ToList();
arrayresult.ForEach(x => {
Console.Write(x + " ");
});
My problem is (a.i) is an error.
Cannot convert 'string' to 'Project.Models.transaction_details'.
you probably mean to check the transaction date. try this:
var query1 = from a in array1Index
select transactions.Any(t => t.Transdate == a.i) == true ? a.i : "";
EDIT:
if you want a list of transactions try this:
var query1 = from t in transactions
where array1Index.Any(a => a.i == t.Transdate)
select t;
var query1 = from t in transactions
where array1Index.Any(a => a.i == t.Transdate);
try this
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
});
I have the following responses from the API. How can I group them into the following structure?
Student[]
- Name
- Classes[]
- ClassName
- ClassId
- ClassCategories[]
- CategoryName
- CategoryWeight
- Assignments[]
- AssignmentName
- Score
I was managed to group them until the "Classes" level but unable to get the ClassCategories for each of the classes
var data = (from result in results
group result by new { result.StudentId, result.FirstName, result.LastName, result.MiddleInitial }
into StudentGroup
select new GroupedStudent
{
StudentId = StudentGroup.Key.StudentId,
FullName = string.Format("{0} {1} {2}", StudentGroup.Key.FirstName, StudentGroup.Key.MiddleInitial, StudentGroup.Key.LastName).Replace(" ", " "),
Classes = from result in results
group result by new { result.ClassId, result.ClassName } into ClassGroup
select new groupedClass
{
ClassName = ClassGroup.Key.ClassName,
ClassId = ClassGroup.Key.ClassId,
ClassCategories = ...
})
}).ToList();
Can anyone please assists me? Thank you.
First, you have make ClassGroup from StudentGroup not from results.
Classes = from s in StudentGroup group result by new { s.ClassId, s.ClassName } into ClassGroup
The complete linq query is as follows:
var data =
(from result in results
group result by new { result.StudentId, result.FirstName, result.LastName, result.MiddleInitial } into StudentGroup
select new
{
StudentId = StudentGroup.Key.StudentId,
FullName = string.Format("{0} {1} {2}", StudentGroup.Key.FirstName, StudentGroup.Key.MiddleInitial, StudentGroup.Key.LastName).Replace(" ", " "),
Classes = (from s in StudentGroup
group s by new { s.ClassId, s.ClassName } into ClassGroup
select new
{
ClassId = ClassGroup.Key.ClassId,
ClassName = ClassGroup.Key.ClassName,
ClassCategories = (from c in ClassGroup
group c by new { c.CategoryName, c.CategoryWeight } into CategoryGroup
select new
{
CategoryName = CategoryGroup.Key.CategoryName,
CategoryWeight = CategoryGroup.Key.CategoryWeight,
Assignments = (from ct in CategoryGroup
group ct by new { ct.AssignmentName, ct.Score } into AssingnmentGroup
select new
{
AssignmentName = AssingnmentGroup.Key.AssignmentName,
Score = AssingnmentGroup.Key.Score
}).ToList()
}).ToList()
}).ToList()
}).ToList();
For example, if you want to access to the first Assignment's score, you can get it like this:
var student = data.FirstOrDefault();
var score = student.Classes[0].ClassCategories[0].Assignments[0].Score;
This is usually how I do It.
Create a class to store your data
Create a list of that class type
In your case instead of string dataRow maybe you can use a sub class
.
// get data from webservice
var json = webClient.DownloadString(url);
var values = JsonConvert.DeserializeObject<JArray>(json);
// create a list to save all the element
List<myClass> classList = new List<myClass>();
// process every row
foreach (string dataRow in values)
{
string[] dataField = dataRow.Split(',');
// have a constructor to assign each value to this element
myClass ctROW = new myClass(dataField);
classList.add(ctROW );
Some background before asking my question.
Im using sql compact, and i have two tables,
The first table (IssueEmp)
The second table (RecEmp)
SqlCeDataAdapter adap = new SqlCeDataAdapter("SELECT * FROM RecEmp", cn);
DataTable dat = new DataTable();
DataSet receice = new DataSet();
adap.Fill(receice);
adap.Fill(dat);
SqlCeDataAdapter adap1 = new SqlCeDataAdapter("SELECT * FROM IssueEmp", cn);
DataTable dat1 = new DataTable();
DataSet issue = new DataSet();
adap1.Fill(issue);
adap1.Fill(dat1);
Im performing a join between RecEmp and IssueEmp using linq
var res = from t1 in receice.Tables[0].AsEnumerable()
join t2 in issue.Tables[0].AsEnumerable()
on new
{
CNo = t1.Field<int>("CNo"),
Empid = t1.Field<int>("EmpID")
}
equals new
{
CNo = t2.Field<int>("CNo"),
Empid = t2.Field<int>("EmpID")
}
select new
{
SNo = t1.Field<int>("SNo"),
ChNo = t1.Field<int>("CNo"),
EmpID = t1.Field<int>("EmpID"),
DateIssued = t2.Field<DateTime>("Date"),
RMIssued = t2.Field<string>("RMCode"),
QuantityIssued = t2.Field<double>("Quantity"),
DateReceived = t1.Field<DateTime>("Date"),
RMCodeReceived = t1.Field<string>("RMCode"),
QuantityReceived = t1.Field<double>("Quantity")
};
The output Im getting from the above linq query is
But I don't know how to get the sum of issued quantity likewise the sum of received quantity, lastly the difference between the two sum as the diff. The required is below.
Note:
I´m a bit lazy so I didn´t use all the records you provided, only the first four records.
Expected result:
This is what I got:
The Linq query:
var query = from d in data
group d by new { d.DateIssued, d.EmpId, d.ChNo, d.DateReceived }
into x
select new {
Date = x.Key.DateIssued,
CNo = x.Key.ChNo,
EmpId=x.Key.EmpId,
CRi = x.Where(c=>c.RMIssued == "CR").Sum(c=>c.QuantityIssued),
SJi = x.Where(c=>c.RMIssued == "SJ").Sum(c=>c.QuantityIssued),
TTi = x.Where(c=>c.RMIssued == "TT").Sum(c=>c.QuantityIssued),
WRi = x.Where(c=>c.RMIssued == "WR").Sum(c=>c.QuantityIssued),
TotalIssued = x.Sum(c => c.QuantityIssued),
DateReceived = x.Key.DateReceived,
CRr = x.Where(c=>c.RMCodeReceived == "CR").Sum(c=>c.QuantityReceived),
SJr = x.Where(c=>c.RMCodeReceived == "SJ").Sum(c=>c.QuantityReceived),
TTr = x.Where(c=>c.RMCodeReceived == "TT").Sum(c=>c.QuantityReceived),
WRr = x.Where(c=>c.RMCodeReceived == "WR").Sum(c=>c.QuantityReceived),
TotalReceived = x.Sum(c => c.QuantityReceived),
Diff = x.Sum(c => c.QuantityIssued) - x.Sum(c => c.QuantityReceived)
};
Data used:
And this is the set of data I used to test it:
var data= new []{
new { SNo= 9, ChNo=5, EmpId=81, DateIssued=dateIssued, RMIssued="SJ", QuantityIssued=30, DateReceived=dateReceived, RMCodeReceived="SJ", QuantityReceived=20.3},
new { SNo= 10, ChNo=5, EmpId=81, DateIssued=dateIssued, RMIssued="SJ", QuantityIssued=30, DateReceived=dateReceived, RMCodeReceived="CR", QuantityReceived=9.6},
new { SNo= 11, ChNo=28, EmpId=82, DateIssued=dateIssued, RMIssued="TT", QuantityIssued=30.5, DateReceived=dateReceived, RMCodeReceived="TT", QuantityReceived=29},
new { SNo= 12, ChNo=28, EmpId=82, DateIssued=dateIssued, RMIssued="WR", QuantityIssued=10, DateReceived=dateReceived, RMCodeReceived="TT", QuantityReceived=29}
};
I recommed you use LinqPad to test it.
Good luck!
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();