简体   繁体   中英

Remove items from multiple nested list using linq

I am having nested list items ParticipantsDetails & AssigneeDetails inside parent list TransactionHistoryDetails .

Both of nested list contains Name Property and I would like to remove items which contain Name as null

Code:

transactionHistory.TransactionHistoryDetails.ForEach(u => u.ParticipantsDetails.RemoveAll(a => a.Name == null));

transactionHistory.TransactionHistoryDetails.ForEach(u => u.AssigneeDetails.RemoveAll(a => a.Name == null));

This code works! But is there any way I can achieve the same in a single line by using || operator?

You cannot achieve this in a single line, because your two calls of RemoveAll operate on two separate collections. You can combine the two lambdas into a single one, like this:

transactionHistory.TransactionHistoryDetails.ForEach(u => {
    u.ParticipantsDetails.RemoveAll(a => a.Name == null);
    u.AssigneeDetails.RemoveAll(a => a.Name == null);
});

Note: There are alternative approaches to this. For example, you can introduce a method on TransactionHistoryDetails to "sanitize" both lists, essentially hiding two RemoveAll lines from sight.

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