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

推荐订阅源

IT之家
IT之家
The GitHub Blog
The GitHub Blog
美团技术团队
Security Latest
Security Latest
The Cloudflare Blog
D
DataBreaches.Net
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
P
Proofpoint News Feed
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Security Affairs
腾讯CDC
H
Hacker News: Front Page
Microsoft Security Blog
Microsoft Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 三生石上(FineUI控件)
C
Check Point Blog
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Cisco Talos Blog
Cisco Talos Blog
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Security Archives - TechRepublic
Security Archives - TechRepublic
I
InfoQ
量子位
Apple Machine Learning Research
Apple Machine Learning Research
AWS News Blog
AWS News Blog
TaoSecurity Blog
TaoSecurity Blog
月光博客
月光博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
D
Docker
Hugging Face - Blog
Hugging Face - Blog
I
Intezer
雷峰网
雷峰网
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
SecWiki News
SecWiki News
N
News and Events Feed by Topic

博客园 - 零零猪

基于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.
================================================================