I've been looking for help on how to find objects in Generics with () 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>();
(new Person(1, "AndreySanches"));
(new Person(2, "AlexandreTarifa"));
(new Person(3, "EmersonFacunte"));
//find a specific object
Person myLocatedObject = (delegate(Person p) {return == 1; });
}
Note: This method is often used to search for elements in list and array collections, the main technique is generic delegates
Note: If you add an object, you must re-new an object, see the following example:
person p=new pewson();
for(int i=0;i<5;i++)
{
=i;
="xxxx";
(p);
}
for(int i=0;i<5;i++)
{
person p=new person();
=i;
="xxxx";
(p);
}
Is there any difference above? There is a difference in the output list value. The first list is stored in the same, and the result is the same as the last one. They are both the same person object. The second list achieves the expected effect and stores different person objects. why is that? The reason is very simple. What is stored in a list object refers to a common object, so the last changed value shall prevail.
Ordering of objects: This article mainly explains sorting the list of datatables by TableName
1. Create a new sort class
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=;
tableNameLength2=;
if (Convert.ToInt32((2,tableNameLength1-2))>Convert.ToInt32((2,tableNameLength2-2)))
return 1; �
else if (Convert.ToInt32((2,tableNameLength1-2))<Convert.ToInt32((2,tableNameLength2-2)))
return -1; �
else
return 0; �
}
}
}
2 Sort:
List<DataTable> ldt = new List<DataTable>();
SceneSort ss=new SceneSort ();
(ss); can sort the list;