.Net 2.0在通用列表中搜索成员对象

时间:2013-02-04 16:28:17

标签: c# list generics search

我正在使用.Net 2.0

我有一个通用的

List< MyContainerObject > MyList;

MyContainerClass MyContainerObject = new MyContainerClass();

Public Class MyContainerClass
{
    public BasicClass BasicObject;
    public AdvanceClass AdvanceObject
}

如何有效地在MyList中搜索BasicObject?

添加了示例代码

namespace WindowsApplication4
{
    public class Program
    {
        private List<ContainerClass> MyList;
        public Program()
        {
            MyList = new List<ContainerClass>();
        }

        private void Add(object sender, EventArgs e)
        {
            ContainerClass objContainer1 = new ContainerClass("B1","A1");
            ContainerClass objContainer1 = new ContainerClass("B2", "A2");
            MyList.Add(objContainer1);
            MyList.Add(objContainer2);            
        }
        private void Get(BasicClass objBasic)
        {
            //How to retreive ContainerClass from MyList that has objBasic ??
        }
    }

    public class ContainerClass
    {
        private BasicClass BasicObject;
        private AdvancedClass AdvancedObject;
        public ContainerClass(string baseID, string AdvanceID)
        {
            BasicObject = new BasicClass();
            BasicObject.ID = baseID;
            AdvancedObject = new AdvancedClass();
            AdvancedObject.ID = AdvanceID;
        }

    }

    public class BasicClass
    {
        public  string ID;
        public int name;
    }

    public class AdvancedClass
    {
        public string ID;
        public int name;
    }
}

2 个答案:

答案 0 :(得分:1)

var found = MyList.FirstOrDefault(o => o.BasicObject == someObject);

请注意,除非BasicObject实现IEquatable<BasicObject>和/或重载Equals / operator==,否则最终会有效object.ReferenceEquals(o.BasicObject, someObject)

糟糕。 .NET 2.0。良好:

BasicObject FindBy(List<MyContainerClass> list, BasicObject o)
{
     foreach (MyContainerClass i in list)
     {
          if (i.BasicObject == o) // same caveats on Equality
              return i;
     }
     return null;
}

答案 1 :(得分:1)

我认为,如果您使用高于2.0的.Net版本,那将是非常好的,因为您可以使用linq来简单地获取您想要的对象列表。

但您可以使用委托和查找方法

http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

可能类似

      MyContainerClass MyContainerObject  = MyList.Find(delegate(MyContainerClass p) {return
 BasicObject.Val == someval; });