简体   繁体   中英

How to Sort a List based on the value of a list within the list in C#?

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..

If you have to sort a list, you have to pick an element which defines the order (like a value, a date, etc.) If the property you like to use for sorting is also a list, you have to either pick one element from that inner list (eg min, max, first, last) or to aggregate all inner list values (like sum, average, median, concat) to one value.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM