学习Linq的两大神器——LinqPad和Resharper

现在我对C#编程已经无法不Linq了,因为它能将我从无数的机械代码中解脱出来,使得写代码和阅读代码变得更像是在创造艺术和欣赏艺术。

这里分享一下以前学Linq的经验。

一:LinqPad:

LinqPad是一个专业的学习Linq的工具,同时也是一个IDE啦,从Linq2SQL到Linq2Xml都提供了很多实例;LinqPad还提供了Linq代码的IL语言代码,对于想研究Linq底层原理的人来说绝对是个难得的好东东。

对于LinqPad的使用这里就不做介绍了,园子里和网上都有很多相关文章。

下载地址:http://www.linqpad.net/

二:ReSharper:

ReSharper是Visual Studio的一个如虎添翼的插件,从代码分析到系统测试等等都提供非常好的支持,相信你一定不会陌生了。

这里只从初学Linq的角度来看看ReSharper在代码重构方面的功能。

ReSharper建议我们使用Linq来写重构代码,初学者往往需要将Linq代码与传统的C#代码进行比较,从而加深对Linq的了解。

如果不会写Linq而又不想去查相关的帮助文档,我们可以直接写成传统的代码,如foreach方式,然后由ReSharper帮我们重构,我们要做的就是学习重构前后的代码。

来个图吧:

 

        public class Account
        {
            public int AId;
            public List<Holding> Holdings;
        }

        public class Holding
        {
            public int HId;
            public List<Transaction> Transactoins;
        }

        public class Transaction
        {
            public int TId;
            public List<TaxLot> TaxLots;
        }

        public class TaxLot
        {
            public double Cost;
        }

        public double GetAllTaxLots(List<Account> accounts)
        {
            double totalCost = 0.0;
            foreach(var account in accounts)
            {
                foreach(var holding in account.Holdings)
                {
                    foreach (var transaction in holding.Transactoins)
                    {
                        foreach (var tax in transaction.TaxLots)
                        {
                            totalCost += tax.Cost;
                        }
                    }
                }
            }
            return totalCost;
        }

函数GetAllTaxLots对传入的账户下的交易费用求和,我们用了四层foreach循环,来看看ReSharper是怎么重构的:

看看重构后的代码吧:

        public double GetAllTaxLots(List<Account> accounts)
        {
            return (from account in accounts
                    from holding in account.Holdings
                    from transaction in holding.Transactoins
                    from tax in transaction.TaxLots
                    select tax.Cost).Sum();
        }

是不是一下子清爽了很多啊,甚至压根就不需要GetAllTaxLots这个函数了是不?

 

posted @ 2012-11-21 14:39  地月银光  阅读(922)  评论(0)    收藏  举报