|
Apologies for the shouting but this is important.
When answering a question please:
- Read the question carefully
- Understand that English isn't everyone's first language so be lenient of bad spelling and grammar
- If a question is poorly phrased then either ask for clarification, ignore it, or mark it down. Insults are not welcome
- If the question is inappropriate then click the 'vote to remove message' button
Insults, slap-downs and sarcasm aren't welcome. Let's work to help developers, not make them feel stupid.
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
For those new to message boards please try to follow a few simple rules when posting your question.- Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
- Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
- Keep the subject line brief, but descriptive. eg "File Serialization problem"
- Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
- Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
- Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
- If you are posting source code with your question, place it inside <pre></pre> tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
- Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
- Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
- Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
- If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
- No advertising or soliciting.
- We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
Dear all,
I'm new in Linq. I have code like the one listed below. Grouping is not working (see output results below) and shows all records.
I would like that it would group by ID and order by birthday (Desc), so I would get results like this:
ID: 1 Name: Arnold; BirthDay: 15.06.2020 00:00:00
ID: 2 Name: Stefan; BirthDay: 15.06.2020 00:00:00
I would appreciate for any help.
class Program
{
public class Student
{
public int ID { get; set; }
public int StandardID { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
static void Main(string[] args)
{
List<Student> studentList = new List<Student>() {
new Student() { ID = 1, Name = "Arnold", Birthdate = new DateTime(2020, 06, 15)},
new Student() { ID = 1, Name = "Arnold", Birthdate = new DateTime(2020, 01, 01)},
new Student() { ID = 2, Name = "Stefan", Birthdate = new DateTime(2020, 06, 15)},
new Student() { ID = 2, Name = "Stefan", Birthdate = new DateTime(2020, 06, 01)},
};
int[] Ids = { 1, 2, 3 };
List<Student> students = studentList
.Where(s => Ids.Contains(s.ID) )
.GroupBy(s => s.ID)
.SelectMany(g => g.OrderByDescending(s => s.Birthdate) ).ToList();
foreach (var i in students)
{
Console.WriteLine($"ID: {i.ID} Name: {i.Name}; BirthDay: {i.Birthdate} ");
}
Console.ReadKey();
}
Results of above:
ID: 1 Name: Arnold; BirthDay: 15.06.2020 00:00:00
ID: 1 Name: Arnold; BirthDay: 01.01.2020 00:00:00
ID: 2 Name: Stefan; BirthDay: 15.06.2020 00:00:00
ID: 2 Name: Stefan; BirthDay: 01.06.2020 00:00:00
|
|
|
|
|
If you think about the data in your grouping;
1
Arnold 15.06.2020
Arnold 01.01.2020
2
Stefan 15.06.2020
Stefan 01.06.2020
When you do SelectMany on that group you are flattening the tree structure one level as you're selecting the children of each parent item so your SelectMany looks like
Arnold 15.06.2020
Arnold 01.01.2020
Stefan 15.06.2020
Stefan 01.06.2020
That's why you're seeing all of the results. What you actually want to do is select the first item in each group after ordering it so change to .Select and do a .First on the ordered group.
List<Student> students = studentList
.Where(s => Ids.Contains(s.ID))
.GroupBy(s => s.ID)
.Select(g => g.OrderByDescending(s => s.Birthdate).First())
.ToList();
|
|
|
|
|
Thank you very much for quick answer!
|
|
|
|
|
I have two linq queries like the following and their output results are correct:
var mytotal = _context.Apiapplicant.Where(c => !c.ApiRequestDate.Equals("") && c.IsDeleted.Equals(false)).GroupBy(o => new
{
Month = o.ApiRequestDate.Substring(5, 2),
Year = o.ApiRequestDate.Substring(0, 4)
}).Select(g => new
{
Month = g.Key.Month,
Year = g.Key.Year,
Total = g.Count()
}).OrderByDescending(a => a.Year).ThenByDescending(a => a.Month).ToList();
The above query gives the total requests that was registerd in each month
var numerator = from t1 in _context.Apiapplicant
join t2 in _context.ApiApplicantHistory on t1.Id equals t2.ApiApplicantId
join t3 in _context.EntityType on t2.LastReqStatus equals t3.Id
//join t4 in mytotal on new { t2.Date.Substring(0,4), t2.Date.Substring(2,5) } equals new { t4.Year, t4.Month }
// join t4 in mytotal on t2.Date.Substring(2, 5) equals t4.Month
where t1.IsDeleted == false && t3.Name == "granted" && t2.Date != null && t1.ApiRequestNo != null
group t1
by new
{
lastReq = t2.LastReqStatus,
Year = t2.Date.Substring(0, 4),
Month = t2.Date.Substring(5, 2)
} into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
lastReq = g.Key.lastReq,
GrantedCount = g.Count()
};
var GrantedReqStatus = numerator.OrderByDescending(x => x.Year).ThenByDescending(a => a.Month).ToList();
The above query gives total requests for each month that has "granted" status. Now I want to find for all the requests that are registered in each month, how many of them has "granted" status. I mean finding how many records in mytotal are in numerator for each month. To obtain it, I've made a query like the following which should join both GrantedReqStatus and mytotal queries:
var LastGrantedStatus = (from t1 in mytotal
from t2 in GrantedReqStatus
where (t1.Month == t2.Month) && (t1.Year == t2.Year)
group t1
by new
{
// lastReq = t2.LastReqStatus,
Year = t1.Year,
Month = t1.Month
} into g
select new { Month=g.Key.Month, Year=g.Key.Year,grcount = g.Count()}).ToList();
But when I run the project, the following expressions doesn't print anything:
I appreciate if anyone can suggest me a solution.
modified 23-Jun-20 13:29pm.
|
|
|
|
|
You already posted this question in the .NET forum. Please do not crosspost.
|
|
|
|
|
I think you're trying to resolve your issue by complicating it too much...
Note, that Count can accept condition to get interesting data (which works like Where ). See: Enumerable.Count Method (System.Linq) | Microsoft Docs
So...
var finalTotal = from t1 in _context.Apiapplicant
join t2 in _context.ApiApplicantHistory on t1.Id equals t2.ApiApplicantId
join t3 in _context.EntityType on t2.LastReqStatus equals t3.Id
where t1.IsDeleted == false && t2.Date != null && t1.ApiRequestNo != null
group t1
by new
{
lastReq = t2.LastReqStatus,
Year = t2.Date.Substring(0, 4),
Month = t2.Date.Substring(5, 2)
} into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
lastReq = g.Key.lastReq,
Granted = g.Count(x=>x.t2.Name == "granted"),
Other = g.Count(x=>x.t2.Name != "granted"),
TotalCount = g.Count()
};
|
|
|
|
|
V
modified 28-Mar-20 13:06pm.
|
|
|
|
|
var dept = departments.OrderByDescending( d => d.DepartmentName.length ).First();
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
I getting this error and cant find reason why ?
System.Data.OleDb.OleDbException: 'Date syntax error in query expression' datumdos BETWEEN # 9.8.2019. # AND # 18.8.2019. # '.'
sql1 = "SELECT * FROM tblpromet WHERE datumdos BETWEEN # 1.1.2019.ToShortDateString() # AND # 10.5.2019.ToShortDateString() #"
da1 = New OleDb.OleDbDataAdapter(sql1, con)
da1.Fill(ds, "PrometBase") ' This Table name
|
|
|
|
|
You are converting the dates to strings, so the comparison will not work as it requires Date types.
|
|
|
|
|
If I change string to :
sql1 = "SELECT * FROM tblpromet WHERE datumdos BETWEEN # 1.1.2019. # AND # 10.5.2019. #"
I have same message, and this are not a string, any suggestion ?
|
|
|
|
|
You should use ISO format of date:
sql1 = "SELECT * FROM tblpromet WHERE datumdos BETWEEN #2019-01-01# AND #2019-05-10#"
|
|
|
|
|
Thanks that is working now I need to change this date with datetimepicker in which is date visible in Eu format dd.MM.yyyy
|
|
|
|
|
No, you don't!
All you have to do is to pass proper date from DateTimePicker, see:
sql1 = String.Format("SELECT * FROM tblpromet WHERE datumdos BETWEEN #{0}# AND #{1}#", DateTimePicker1.Value, DateTimePicker2.Value)
Date is a date. Its format is for string representation only!
|
|
|
|
|
That's a SQL query you've just injected user-controlled values into.
It might be OK with dates, but it's still a bad habit and should be discouraged.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
|
|
This is perfect only how to add more filters like :
FROM tblpromet WHERE kod like '" & txttrkod.Text & "%'and obrada like '" & txtobrada & "%' order by kod"
|
|
|
|
|
In exactly the same way:
Const query As String = "SELECT * FROM tblpromet WHERE kod like ? AND obrada like ? ORDER BY kod"
da1 = New OleDb.OleDbDataAdapter(query, con)
da1.SelectCommand.Parameters.AddWithValue("kod", txttrkod.Text & "%")
da1.SelectCommand.Parameters.AddWithValue("obrada", txtobrada.Text & "%")
da1.Fill(ds, "PrometBase")
You just have to make sure to add the parameters in the same order that the ? placeholders appear in the query, since you can't use named parameters.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The error is with in the query string. Between keyword does not work well with string datatype.
|
|
|
|
|
Hai Friends,I am a beginner to Csharp.So please help me.My Query is :I have created datatable in datagridview and inserted columns and rows in that table.how to get last row value in a data table.
please clarify in simple way.
|
|
|
|
|
|