过滤IList <t> </t>

时间:2011-04-11 13:31:15

标签: asp.net c#-4.0 pass-by-reference ilist pass-by-value

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

2 个答案:

答案 0 :(得分:3)

使用LINQ:

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

答案 1 :(得分:0)

您可以使用List<T> copy constructor并从副本中删除:

var paymentOptionsWithNoInvoice = new List<PaymentType>(_PaymentMethods);
paymentOptionsWithNoInvoice.RemoveAll(pt => noInvoice.Contains(pt.Id));