C#中List用法
2019獨角獸企業重金招聘Python工程師標準>>>
How to find objects in Generics with List.Find() method
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進行排序;
轉載于:https://my.oschina.net/duluo180/blog/10717
總結
- 上一篇: 今天感觉有点冷了其实。
- 下一篇: 企业IT解决方案经验分享活动