Search code examples
asp.netc#-4.0pass-by-referenceilistpass-by-value

Filter IList<T>


List<PaymentType> paymentOptions = _PaymentMethods;

_PaymentMethods is an public property and I'd like to filter a copy of it and store it in the variable paymentOptions

List<Int32> noInvoice = new List<Int32>(){ 16, 4 , 6 };
foreach (PaymentType pt in paymentOptions)
{
    if(noInvoice.Contains(pt.Id))
    {
        paymentOptions.Remove(pt);
        break;
    }
}

But if you run this the second time, the variable _PaymentMethods does not contain the removed item anymore.

It seems to go by Reference instead of by value... I prefer not to copy the list to an array Should I use Linq or is there an other way?

EDIT: I have this now:

List<PaymentType> paymentOptions = ShopController.CurrentShop.PaymentMethods;
List<PaymentType> paymentOptionsFiltered = new List<PaymentType>();    

if (haveToFilter)
{
    List<Int32> noInvoice = new List<Int32>() { 16, 4, 6 };

    foreach (PaymentType pt in paymentOptions)
    {
        if (!noInvoice.Contains(pt.Id))
        {
            paymentOptionsFiltered.Add(pt);
        }
    }
    repeaterPaymentOptions.DataSource = paymentOptionsFiltered;
}
else
{
    repeaterPaymentOptions.DataSource = paymentOptions;
}

Solution

  • Use LINQ:

    List<PaymentType> paymentOptionsWithNoInvoice =  
    paymentOptions.Where(a=> !noInvoice.Contains(a.Id)).ToList();