已检查项目带有对象集合的CheckedListBox

时间:2013-12-31 04:56:36

标签: c# extension-methods generic-list generic-collections

我使用我的通用列表进行checkedlistbox绑定。我需要根据值检查项目。因为我使用对象集合绑定我需要转换对象并检查id。为此我使用了以下循环并且它被取代

if (currentDeliveryNote.Quotations != null)
{
      foreach (QuotationBase item in currentDeliveryNote.Quotations)
      {
           for (int i = 0; i < chklstQuotation.Items.Count; i++)
           {
                if (((QuotationBase)chklstQuotation.Items[i]).ID == item.ID)
                {
                     chklstQuotation.SetItemChecked(i, true);
                }
           }
      }
}

现在,同样的概念也适用于所有其他页面。但唯一的区别是对象名称不同。例如:在此页面中,这是QuotationBase。对于下一页,这是DeliveryNote,另一页是Invoice等。

那我怎么写一个通用的扩展方法来检查项目。所有对象都有ID属性,用于与列表进行比较以进行检查。

1 个答案:

答案 0 :(得分:1)

您需要将ID属性放在界面上,然后才能使用泛型:

public static void CheckItems<T>(this IEnumerable<T> items, CheckList checkList) where T : IIdentifiable
{
    if (items != null)
    {
        foreach (T item in items)
        {
           for (int i = 0; i < checkList.Items.Count; i++)
           {
                if (((T)checkList.Items[i]).ID == item.ID)
                {
                     checkList.SetItemChecked(i, true);
                }
           }
        }
    }
}

public interface IIdentifiable
{
    string ID { get; }
}

public class Quotationbase : IIdentifiable
...
相关问题