Linq with ArrayList and List of user define Class (2010-01-05)
......
......
static void Main(string[] args)
{
ArrayList al = new ArrayList();
al.Add(new Person("Chiwa",25));
al.Add(new Person("Chiwa2",26));
al.Add(new Person("Chiwa3",27));
al.Add(new Person("Chiwa4",28));
var person =
from Person p in al
select p;
foreach(var p in person)
{
Console.WriteLine(p.name+" "+p.age);
p.echo();
}
Console.ReadLine();
}//================================//
}//end class
//==================================//
class Person
{
public string name;
public int age;
public Person(String n, int a)
{
this.name = n;
this.age = a;
}
public void echo()
{
Console.WriteLine("Echo ==> "+this.name);
}//========================//
}
//======================================//
ใส่ condition ก็ได้นะเช่น
var person =
from Person p in al
where p.age <= 26 && ............
select p;
แล้วถ้าผมจะหาอายุเฉลี่ยล่ะ ก็แค่นี้ครับ
var av = person.Average(p => p.age);
Console.WriteLine("average age is {0} .", av);
ลองใช้ List ดู ก็ง่ายดี
Console.WriteLine("=================USE LIST================");
List<Person> Persons = new List<Person>();
Persons.Add(new Person("Chiwa", 25));
Persons.Add(new Person("Chiwa2", 26));
Persons.Add(new Person("Chiwa3", 27));
Persons.Add(new Person("Chiwa4", 28));
var avr = Persons.Where(p => p.age >= 27).Sum(p => p.age);
Console.WriteLine("Sum age is {0} .", avr);
Console.ReadLine();
|