惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 零零猪

基于Windows Server 2008 R2的Failover Cluster(故障转移群集)部署Sql Server 2008 AA(主主) 模式群集(第二部分) - 零零猪 基于Windows Server 2008 R2的Failover Cluster(故障转移群集)部署Sql Server 2008 AA(主主) 模式群集(第一部分) - 零零猪 整型运算三个恒等式 Office 2010众多客户端产品、服务器产品试用下载 免费发短信,短信云计算?? - 零零猪 Asp.Net MVC 1.0 Action Filters Tips 暂时做一个快乐的SOHO族 Asp.Net MVC使用HtmlHelper渲染,并传递FormCollection参数的陷阱 ASP.Net MVC Relational KeyWord 4 Google 【More...】【欢迎补充】 本博客加入“署名-非商业性使用-禁止演绎 2.5 中国大陆”许可协议 Exchange 2007 队列数据库、队列事务日志文件超过临界值(阈值)导致无法接受邮件解决方案 10步完成Windows 2003+SQLServer 2005 群集(Cluster)安装及配置【备案】 photosynth Trial - 零零猪 MOSS 2007 爬网规则 Contentclass常用属性设置 有用的SharePoint英文资源[持续更新] MOSS2007中Feature对象模型操作 - 零零猪 SQL日志收缩(ZZ) Microsoft photosynth(图片三维展示) - 零零猪 MOSS2007匿名调查列表使用分页符导致的错误分析
C# 3.0通过Linq、Lambda、匿名函数、代理函数实现数据查询
零零猪 · 2009-09-08 · via 博客园 - 零零猪

      这几天,正在学习Linq、Lambda,做了些实验,通过Linq、Lambda、匿名函数、代理函数4种方式实现一个简单的查询,把实现结果记录一下,以免忘记。
      这段代码中有一个Person类,包含Name和Age两个属性。
      还有一个PersonHelper类(这个类规划不是很合理,只是做实验用下),包含一个强类型的List<Person>,并提供了4种实现数据查询的方法(都是查询年龄大于5的人员信息,并返回):

//方法1:通过Linq返回大于某个年龄段的人
public IEnumerable<Person> GetPersonByLinq(int age)//方法2:通过Lambda表达式返回大于某个年龄段的人
public IEnumerable<Person> GetPersonByLambda(int age)//方法3:通过匿名函数返回大于某个年龄段的人
public IEnumerable<Person> GetPersonByAnonymouseMethod(int age)//方法4:通过代理函数返回大于某个年龄段的人(由于代理函数传递年龄参数不方便,代理函数是通过外部函数完成的)
public IEnumerable<Person> GetPersonBydelegate(Func<Person,bool> func)

下面是完整的代码(VSTS 2008,基于 .Net 3.0 的控制台工程)

  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Text;
  5
  6namespace LinqTest
  7{
  8    class Program
  9    {
 10        static void Main(string[] args)
 11        {
 12
 13            PersonHelper helper = new PersonHelper();
 14
 15            //初始化Person类(0-6岁),并把结果放入list列表
 16            for (int i = 0; i < 7; i++)
 17            {
 18                Person p = new Person() 
 19                { Name = string.Format("Jiessieliang{0}", i.ToString()), Age = i };
 20
 21                helper.List.Add(p);
 22            }

 23
 24            //方法1:通过Linq返回岁数大于5的人员集合
 25            IEnumerable<Person> results = helper.GetPersonByLinq(5);
 26            Print(results);
 27
 28
 29            //方法2:通过Lambda表达式返回岁数大于5的人员集合
 30            IEnumerable<Person> results1 = helper.GetPersonByLambda(5);
 31            Print(results1);
 32
 33
 34
 35            //方法3:通过匿名方法返回岁数大于5的人员集合
 36            IEnumerable<Person> results2 = helper.GetPersonByAnonymouseMethod (5);
 37            Print(results2);
 38
 39
 40            //方法4:通过代理函数返回岁数大于5的人员集合
 41
 42            //定义一个代理【protected static bool getByAge(Person person)】
 43            Func<Person, bool> func = new Func<Person, bool>(getByAge);
 44
 45            //通过代理函数返回岁数大于5的人员集合
 46            IEnumerable<Person> results3 = helper.GetPersonBydelegate(func);
 47            Print(results3);
 48
 49
 50            Console.Read();
 51        }

 52
 53        /// <summary>
 54        /// 方法4中 最终被调用执行的代理函数
 55        /// </summary>
 56        /// <param name="person"></param>
 57        /// <returns></returns>

 58        protected static bool getByAge(Person person)
 59        {
 60            return person.Age > 5;
 61        }

 62
 63        /// <summary>
 64        /// 打印信息到屏幕
 65        /// </summary>
 66        /// <param name="results"></param>

 67        static void  Print(IEnumerable<Person> results)
 68        {
 69
 70            foreach (Person person in results)
 71            {
 72                Console.WriteLine(string.Format("Name is : {0} , Age is : {1}", person.Name, person.Age));
 73            }

 74        }
  
 75    }

 76
 77    /// <summary>
 78    /// Person类
 79    /// </summary>

 80    public class Person
 81    {
 82        public Person()
 83        { }
 84        private string _name;
 85
 86        public string Name
 87        {
 88            get return _name; }
 89            set { _name = value; }
 90        }

 91        private int _age;
 92
 93        public int Age
 94        {
 95            get return _age; }
 96            set { _age = value; }
 97        }

 98
 99    }

100
101    /// <summary>
102    /// PersonHelper类
103    /// </summary>

104    public class PersonHelper
105    {
106        /// <summary>
107        /// 存放Person的列表
108        /// </summary>

109        List<Person> _list;
110
111        public List<Person> List
112        {
113            get return _list; }
114          
115        }

116
117        public PersonHelper()
118        {
119            _list = new List<Person>();
120          
121        }

122
123        /// <summary>
124        /// 方法1:通过Linq返回结果
125        /// </summary>
126        /// <param name="age"></param>
127        /// <returns></returns>

128        public IEnumerable<Person> GetPersonByLinq(int age)
129        {
130            return from ps in List
131                   where ps.Age > age
132                   select ps;
133        }

134
135        /// <summary>
136        /// 方法2:通过Lambda返回结果
137        /// </summary>
138        /// <param name="age"></param>
139        /// <returns></returns>

140        public IEnumerable<Person> GetPersonByLambda(int age)
141        {
142            return Enumerable.Where<Person>(List, ps => (ps.Age > age));
143        }

144
145        /// <summary>
146        /// 方法3:通过匿名方法返回结果
147        /// </summary>
148        /// <param name="age"></param>
149        /// <returns></returns>

150        public IEnumerable<Person> GetPersonByAnonymouseMethod(int age)
151        {
152
153            return Enumerable.Where<Person>(List, 
154                delegate(Person ps) return ps.Age > age; });
155        }

156
157        /// <summary>
158        /// 方法4:通过代理函数返回结果
159        /// </summary>
160        /// <param name="func"></param>
161        /// <returns></returns>

162        public IEnumerable<Person> GetPersonBydelegate(Func<Person,bool> func)
163        {
164            return Enumerable.Where<Person>(List, func);
165        }

166    }

167}

最终输出结果为:
Name is : Jiessieliang6 , Age is : 6
Name is : Jiessieliang6 , Age is : 6
Name is : Jiessieliang6 , Age is : 6
Name is : Jiessieliang6 , Age is : 6

同一个查询,可以通过Linq,Lambda表达式,匿名方法和代理来实现。

================================================================
转载要求及授权协议:
作者
零零猪(or)Jiessie327(or)JiessieLiang 
出处http://jiessie327.cnblogs.com/
版权:本文版权归作者所有
转载:欢迎转载,为了尊重作者的劳动成果,在【转载】时请按作者要求,指明文章【出处】或给出【原文链接】,谢谢
================================================================

请遵守署名-非商业性使用-禁止演绎 2.5 中国大陆 License.
================================================================