rajesh yadav

rajesh yadav

  • 1.6k
  • 82
  • 9.8k

should we put order by in list of objects while returning.

Apr 10 2020 2:53 AM

public class pdate
{

public DateTime ProgressDate { get; set; }

public prog decimal{get;set;]

}

List<pdate> listpdate = new List<pdate>();
SCurve scurveObj = null;

DateTime dtFrom1 = DateTime.SpecifyKind(Convert.ToDateTime("01 jan 2019").Date, DateTimeKind.Utc);
DateTime dtTo1 = DateTime.SpecifyKind(Convert.ToDateTime("01 feb 2019").Date, DateTimeKind.Utc);

for (DateTime i = dtFrom1; i <= dtTo1; i = i.AddDays(1))
{
pdate = new pdate();

pdate.ProgressDate = i.Date;

pdate.prog = 10;

listpdate.Add(pdate);

}

this code is in api which returns listpdate;

Q1) in return stmt should i put order by or will it keep the order in which i have inserted the objects, and finally the api is called in .js so will get every thing in the same order

in which i have entered.

return listpdate.OrderBy(o => o.ProgressDate).ToList();

q2) if i group by on one col in return stmt , then should we use order by or it will keep the objects in listpdate ordered by progressdate in the order i have entered in loop.

so in simple should i put ordeby or not in this case. where i need the data at .js on page order by progress date.

return listpdate.GroupBy(val => DateTime.SpecifyKind(new DateTime(val.ProgressDate.Year, val.ProgressDate.Month,
DateTime.DaysInMonth(val.ProgressDate.Year, val.ProgressDate.Month)),DateTimeKind.Utc))
.Select(grouped => new pdate()
{
ProgressDate = grouped.Key
,
prog = grouped.Sum(Pp => Pp.prog)
}).OrderBy(o => o.ProgressDate).ToList();

Answers (3)