日期:2014-05-20  浏览次数:20851 次

求Lamba表达式
C# code

    class Program
    {
        static void Main(string[] args)
        {

        }

        // 求Lambda表达式,返回一个string类型。
        static string Cash()
        {
            string typeInfo = string.Empty;
            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}
            };
            foreach (var p in pros)
            {
                if (p.TypeName == "类型2")
                {
                    switch (p.Type)
                    {
                        case "1": typeInfo = "型号1"; break;
                        case "2": typeInfo = "型号2"; break;
                    }
                }
            }
            return typeInfo;
        }
    }
    struct Product
    {
        public string TypeName;
        public string Type;
        public double 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 v = pros.Where(x => x.TypeName == "类型2").Select(x =>x.Type=="1"? 型号1:型号2);

------解决方案--------------------


C# code
        static string Cash()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("1", "类型1");
            dict.Add("2", "类型2");
            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 = (from x in pros
                        join y in dict on x.TypeName equals y.Value into j
                        select j.Key).Last();
            return query;
        }