0
List<PaymentType> paymentOptions = _PaymentMethods;

_PaymentMethods是公共财产,我想过滤它的副本并将其存储在变量中paymentOptions

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

但是,如果您第二次运行,该变量_PaymentMethods将不再包含已删除的项目。

它似乎是按引用而不是按值...我不想将列表复制到数组我应该使用 Linq 还是有其他方法?

编辑:我现在有这个:

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;
}
4

2 回答 2

3

使用 LINQ:

List<PaymentType> paymentOptionsWithNoInvoice =  
paymentOptions.Where(a=> !noInvoice.Contains(a.Id)).ToList();
于 2011-04-11T13:33:56.077 回答
0

您可以使用List<T> 复制构造函数并从副本中删除:

var paymentOptionsWithNoInvoice = new List<PaymentType>(_PaymentMethods);
paymentOptionsWithNoInvoice.RemoveAll(pt => noInvoice.Contains(pt.Id));
于 2011-04-11T13:40:31.193 回答