读书人

求Lamba表达式解决思路

发布时间: 2013-01-08 14:02:13 作者: rapoo

求Lamba表达式


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;
}

[解决办法]

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);


[解决办法]


        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;
}

读书人网 >.NET

热点推荐