LINQ中的案例和IIF

时间:2016-02-11 10:09:16

标签: c# asp.net linq sql-server-2012

我如何在LINQ ASP.Net中获得相同的结果,因为SQL以下select *, case when gender = 1 then 'Male' else 'Female' end as gen from info 次查询

以防

select iif(gender = 1, 'Male', 'Female') as gen, * from info 

和iif

InfoDataContext db = new InfoDataContext();

            var data = from y in db.infos
                       db.infos.Select(i => new info{info = i, i.gender == 1 ? "Male" : "Female"}).ToList()
                       select y;

            GridView1.DataSource = data;
            GridView1.DataBind();

我尝试使用建议,但抛出错误

gen

另外一个是,第一个查询将新结果作为表中的最后一列返回,第二个查询作为表中的第一列返回。如何使用gender列重新排列或替换http

2 个答案:

答案 0 :(得分:7)

只需使用三元运算符:

var data = context.info.Select(i => new {info = i, gender = i.gender == 1 ? "Male" : "Female"}).ToList();

答案 1 :(得分:0)

我已经完成了你的建议。

InfoDataContext db = new InfoDataContext();
            var dat = db.infos.Select(i => new {info = i,i.id, i.name, Gen= i.gender == true ? "Male" : "Female", i.city});
            GridView1.DataSource = dat;
            GridView1.DataBind();