在List中停止重复

时间:2013-04-26 14:41:59

标签: c# asp.net

我有一个网格,其中有几个下拉列表,我想要的是,当用户插入新数据时,检查列表中是否已存在相同的数据。

我的代码就像这样

if(ViewState["_priceSystems"]!=null)
    _priceSystems=ViewState["_priceSystems"] as TList<PriceSystemItems>;

bool _isTrue=
    PriceSystemExist(
        _priceSystemItems.PricePlanId,
        _priceSystemItems.SurchargePlanId,
        _priceSystemItems.NoMatchAltPlanId);

if(_isTrue==false) {
    _priceSystems.Add(_priceSystemItems);
}

这里我在_priceSystems列表中添加了值&lt;&gt;以下代码我正在检查该值是否存在于列表中

public bool PriceSystemExist(
    int PricePlanId, int SurchagePlanId, int _noPlaneId) {
    bool isExits=false;

    if(ViewState["_priceSystems"]!=null)
        _priceSystems=ViewState["_priceSystems"] as TList<PriceSystemItems>;
    try {
        if(_priceSystems!=null) {
            foreach(PriceSystemItems item in _priceSystems) {
                if(
                    item.PricePlanId==_priceSystemItems.PriceSystemId
                    &&
                    item.ServiceTypeId==_priceSystemItems.ServiceTypeId
                    &&
                    item.NoMatchAltPlanId==_priceSystemItems.NoMatchAltPlanId) {
                    isExits=true;
                }
            }
        }
    }
    catch(Exception ex) {
    }

    return isExits;
}

我不明白我在foreach循环中检查值的错误。

2 个答案:

答案 0 :(得分:0)

将比较方法更改为

   public bool PriceSystemExist(int PricePlanId, int SurchagePlanId, int _noPlaneId)
   {
      bool isExits = false;
      if (ViewState["_priceSystems"] != null)
      _priceSystems = ViewState["_priceSystems"] as TList<PriceSystemItems>;
    try
    {
      if(_priceSystems != null)
      {
          foreach (PriceSystemItems item in _priceSystems)
         {
            if (item.PricePlanId == PricePlanId &&  item.ServiceTypeId == SurchagePlanId && item.NoMatchAltPlanId ==  _noPlaneId)
        {
            isExits = true;
        }
     }
  }

 }
 catch (Exception ex)
 {

 }

 return isExits;
}

答案 1 :(得分:0)

您没有在PriceSystemExist(int PricePlanId, int SurchagePlanId, int _noPlaneId)方法中使用参数。

使用

PricePlanId
SurchagePlanId 
_noPlaneId

而不是

_priceSystemItems.PriceSystemId
_priceSystemItems.ServiceTypeId
_priceSystemItems.NoMatchAltPlanId

在您的条件中。

foreach (PriceSystemItems item in _priceSystems)
{
        if (item.PricePlanId == PricePlanId && 
            item.ServiceTypeId == SurchagePlanId && 
            item.NoMatchAltPlanId == _noPlaneId)
        {
            isExits = true;
        }
 }

你不想混合你的_前缀。

相关问题