C#用Lambda表达式操作List集合

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.MobileControls;

namespace WebFormTest.TestCollect
{
    public partial class ListOprator : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            People p1 = new People() { Age = 10, Name = "张三", Birth = Convert.ToDateTime("1988-10-1") };
            People p2 = new People() { Age = 18, Name = "张三2", Birth = Convert.ToDateTime("1966-10-2") };
            People p3 = new People() { Age = 12, Name = "张三3", Birth = Convert.ToDateTime("1999-10-3") };
            List list = new List();
            list.Add(p1);
            list.Add(p2);
            list.Add(p3);

            list = list.Select(p => p).ToList(); //获取所有
            list = list.OrderByDescending(s => s.Age).ToList(); //排序
            list = list.Where(s => (s.Age == 18 || s.Name=="张三3") ).ToList(); //筛选

            foreach (var item in list)
            {
                string str = string.Format("姓名:{0},年龄:{1},生日:{2}
", item.Name, item.Age, item.Birth); Response.Write(str); } } } class People { private int age; public int Age { get { return age; } set { age = value; } } private string name; public string Name { get { return name; } set { name = value; } } private DateTime birth; public DateTime Birth { get { return birth; } set { birth = value; } } } }

 

你可能感兴趣的:(C#)