首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

这段代码用Lambda表达式该怎么编写

2012-05-04 
这段代码用Lambda表达式该如何编写C# codeclass Program{static void Main(string[] args){}//这个方法用L

这段代码用Lambda表达式该如何编写

C# code
    class Program    {        static void Main(string[] args)        {        }        //这个方法用Lambda可以编写吗?要返回一个int类型,对Lambda各种不懂。        static int Cash()        {            int price = 0;            List<Product> pros = new List<Product>()            {                new Product(){TypeName="类型1",Type="1",Price=20},                new Product(){TypeName="类型2",Type="1",Price=24},                new Product(){TypeName="类型3",Type="2",Price=12}            };            for (int i = 0; i < pros.Count; i++)            {                if (pros[i].TypeName == "类型1")                {                    price = Convert.ToInt32(pros[i].Price);                }            }            return price;        }    }    class Product    {        public string TypeName;        public string Type;        public double Price;    }


[解决办法]
C# code
new List<Product>()            {                new Product(){TypeName="类型1",Type="1",Price=20},                new Product(){TypeName="类型2",Type="1",Price=24},                new Product(){TypeName="类型3",Type="2",Price=12}            }.Where(x=>x.TypeName=="类型1").Select(x=>int.Parse(x.Price)).First();
[解决办法]
new List<Product>()
{
new Product(){TypeName="类型1",Type="1",Price=20},
new Product(){TypeName="类型2",Type="1",Price=24},
new Product(){TypeName="类型3",Type="2",Price=12}
}.Where(x=>x.TypeName=="类型1").Select(x=>new{int.Parse(x.Price)}).First();

[解决办法]
C# code
        struct Product        {            public string TypeName;            public string Type;            public float Price;        }        private void button10_Click(object sender, EventArgs e)        {            List<Product> pros = new List<Product>()            {                new Product(){TypeName="类型1",Type="1",Price=20},                new Product(){TypeName="类型2",Type="1",Price=24},                new Product(){TypeName="类型3",Type="2",Price=12}            };            var v = pros.Where(x => x.TypeName == "类型1").Select(x => new { x.Price });        }
[解决办法]
C# code
  List<Product> pros = new List<Product>()            {                new Product(){TypeName="类型1",Type="1",Price=20},                new Product(){TypeName="类型2",Type="1",Price=24},                new Product(){TypeName="类型3",Type="2",Price=12}            };  var query=pros.Where(x=>x.TypeName=="类型1").Select(x=>Convert.ToInt32(x.Price)).DefaultOrFirst(); 

热点排行