Probably the question is a bit confusing but basically I have a list which inside consisting another list. Like this:
public class Transaction
{
public string TransactionType { get; set; }
public List<TransactionDetails> Details { get; set; } = new List<TransactionDetails>();
}
public class TransactionDetails
{
public string TransactionDate { get; set; }
public double TransactionAmount { get; set; }
public double TransactionBalance { get; set; }
}
Now, I want to sort the Transaction list based on the TransactionDate inside the TransactionDetails list. If let's say I just want to sort it based on TransactionType, I know that this is the way to do it: (assuming I already added the list)
List<Transaction> listTransactions;
List<Transaction> sortedListTransactions;
sortedListTransactions = listTransactions
.OrderBy(x => x.TransactionType)
.ToList();
I tried it and this worked. But, when I applied basically the same method for my case,which is to sort the list based on TransactionDate, it doesnt give me the answer I needed. Please let me know if there is any way I could achieve this..
CodePudding user response:
If you want to sort by a inner list, the first question is, which value of the inner list should be taken for comparison with other elements also holding a list?
One approach in your case could be to find the minimum element within the inner list and use this as criteria for sorting the outer elements. This could be something like this:
var sortedTransactions = transactions
.OrderBy(transaction => transaction.Details
.OrderBy(detail => detail.TransactionDate)
.FirstOrDefault())
.ToList();
From your example another possibility to sort the outer elements from the inner list, could be to take the sum of amount of all transactions, which would be something like this:
var sortedTransactions = transactions
.OrderBy(transaction => transaction.Details
.Sum(detail => detail.TransactionAmount))
.ToList();
Nevertheless, it is up to you to define the criteria of sorting on every level and then let it bubble up to give the sorting criteria back.
