Search code examples
c#arrayslinqremoveall

Remove element from list using linq


I have and object of type ct_CompleteOrder and have following classes:

ct_CompleteOrder class

public partial class ct_CompleteOrder {
    private ct_CompleteOrderPayments paymentsField;
}

ct_CompleteOrderPayments class

public partial class ct_CompleteOrderPayments {
    private ct_Payment[] paymentField;
    public ct_Payment[] Payment {
    get {
        return this.paymentField;
        }
    set {
        this.paymentField = value;
        }
    }
}

ct_Payment class

public partial class ct_Payment {
    public string type{get; set;}
}

I want to remove elements of the ct_Payment array on the basis of type value. I tried to convert it into list first to apply RemoveAll, but its not working. what am I doing wrong?

completeOrder.Payments.Payment.ToList().RemoveAll(x => x.type == "AUTO");

Solution

  • When you copy the array to list and then apply linq, the link is only removing from the list, not from the array.

    If you want to keep the array the same size, but with empty spaces, you should walk through the array using a for loop and set any that have x.type == "AUTO" to null.

    for(int i = 0; i < completeOrder.Payments.Payment.Length; i++)
    {
        if(completeOrder.Payments.Payment[i].type == "AUTO")
        {
            completeOrder.Paymets.Payment[i] == null;
        }
    }
    

    Otherwise, if you want the actual size of the array to change just set payment to the altered list. RemoveAll DOES NOT return the list (it returns void), so you might as well reverse your logic and just use a Where statement

    completeOrder.Payments.Payment = completeOrder.Payments.Payment.Where(x => x.type != "AUTO").ToArray();