首页 > 编程 > C# > 正文

List<>中Find的用法小结

2020-01-24 02:51:11
字体:
来源:转载
供稿:网友

I've been looking for help on how to find objects in Generics with List.Find() method .... and ... take a look what I have found.
In the follow example, I created a simple class:

复制代码 代码如下:

public class Person
{
       private int _id;
       private string _name;

       public int ID {  get{ return _id;} set{ _id = value;}}
       public int Name {  get{ return _name;} set{ _name= value;}}

       public Person(int id, string name)
       {
             _id = id;
             _name = name;
       }
}


In the example, there's a simple class with two private attributes. Now we're going to create a typed List of this object and take advantage of the Find() method
复制代码 代码如下:

public void CreateAndSearchList()
{
      //create and fill the collection
      List<Person> myList = new List<Person>();
      myList.Add(new Person(1, "AndreySanches"));
      myList.Add(new Person(2, "AlexandreTarifa"));
      myList.Add(new Person(3, "EmersonFacunte"));

     //find a specific object
     Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });
}


备注:在list和array集合中搜索元素经常使用该方法,主要技术是泛型委托

list用法注意:如果增加一个对象,必须重新new一个对象,看下面的例子:

复制代码 代码如下:

person p=new pewson();
for(int i=0;i<5;i++)
{
p.ID=i;
p.Name="xxxx";
list.add(p);
}

for(int i=0;i<5;i++)
{
person p=new person();
p.ID=i;
p.Name="xxxx";
list.add(p);
}


上面有区别吗?在输出list的值是有区别了,第一个list里面存放的都是一样的,结果和最后一个一样,都是同一个人对象,第二个list达到预期的效果,存储不同的人对象。这是为什么?原因很简单,一个list对象中存储的都是对一个共有的对象进行引用,所以以最后改变的值为准。

对象的排序:本文主要阐述对存储datatable的list进行按TableName排序

1、新建一个sort类

复制代码 代码如下:

public class SceneSort:IComparer<DataTable>
    {
       public int Compare(DataTable obj1, DataTable obj2)
       {
           int tableNameLength1;
           int tableNameLength2;
           if (obj1 == null)
           {
               if (obj2 == null)
                   return 0;
               else
                   return -1;
           }
           else
           {
               if (obj2 == null)
                   return 1;
               else
               {
                   tableNameLength1=obj1.TableName.Length;
                   tableNameLength2=obj2.TableName.Length;
                   if (Convert.ToInt32(obj1.TableName.Substring(2,tableNameLength1-2))>Convert.ToInt32(obj2.TableName.Substring(2,tableNameLength2-2)))
                       return 1;                            //大于返回1
                   else if (Convert.ToInt32(obj1.TableName.Substring(2,tableNameLength1-2))<Convert.ToInt32(obj2.TableName.Substring(2,tableNameLength2-2)))
                       return -1;                           //小于返回-1
                   else
                       return 0;                            //相等返回0
               }
           }

       }


2 排序:
List<DataTable> ldt = new List<DataTable>();
SceneSort ss=new SceneSort ();
tablelist.sort(ss);即可对list进行排序;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表