I am getting list of rows from the DB (which I am passing back to my controller and then processing in the view with Razor syntax), but I am not able to sort the list by a specific DB column.
public class GetTableDetails
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
public string Column4PDT { get; set; }
public string Column5 { get; set; }
public static List<GetTableDetails> GetDetails(ApplicationDbContext _context)
{
var tableEntriesCount = _context.TableName.Count();
var Table = _context.TableName.FirstOrDefault();
string[,] table = { };
List<GetTableDetails> mainList = new List<GetTableDetails>();
List<string> column1List = _context.TableName.Where(c => c.Column1Title != null).Select(c => c.Column1Title).ToList();
List<string> column2List = _context.TableName.Where(c => c.Column2Title!= null).Select(c => c.Column2Title).ToList();
List<string> column3List = _context.TableName.Where(c => c.Column3Title!= null).Select(c => c.Column3Title).ToList();
List<DateTime> postedDateTimeList = _context.TableName.Where(c => c.PostedDateTime != null).Select(c => c.PostedDateTime.Value).ToList();
List<string> column5List = _context.TableName.Where(c => c.Column5Title!= null).Select(c => c.Column5Title).ToList();
for (int i = 0; i < tableEntriesCount; i++)
{
rows = new string[,] { { column1List[i], column2List[i], column3List[i], postedDateTimeList[i].ToString(), column5List[i] } };
mainList.Add(new GetTableDetails() { Column1 = rows[0, 0], Column2 = rows[0, 1], Column3 = rows[0, 2], Column4PDT = rows[0, 3], Column5 = rows[0, 4] });
}
return mainList;
}
}
I have tried variations of mainList.OrderByDescending(p => p.PostedDateTime); at the bottom of the GetCardDetails class before returning the list. But I keep getting a variety of errors.
I have also tried sorting the DB table (Rather than my list) before getting the values but despite trawling Google I cant figure this out, the Entity Frameworks docs seem more complicated that what I need to do. The below inserted at the top of the GetCardDetails class doesnt throw an error, but doesnt do anything and is not applying any changes to the DB table.
_context.TableName.OrderByDescending(p => p.PostedDateTime);
_context.SaveChangesAsync();
I'm also not sure what 'best practice' is here. Sort the list or sort the table before creating the list. I figure sorting the list would be more efficient.
Can anyone help with how I can sort the list by the PostedDateTime column please?