日期:2014-05-18  浏览次数:20416 次

求Linq 语句,[面试题]


这个数据源,用下面的sql 语句,可以转成如下结果://好象有点复杂了。

SQL code
select count([t0].id),avg([t0].Fsalary),[t0].年龄段 from
(
    select id,
    (
        case 
            when (Fage<20) then '<20'
            when (Fage>=20 and Fage<30)then '20 -30'
            when (Fage>=30 and Fage<40)then '30 -40'
            when (Fage>=40  )then '>40'
            else 'error'
            end
    )  AS    '年龄段', 
    FAge ,
    FName,
    fsalary
    from T_Employee 
) as [t0] 
group by [t0].年龄段

 [人数] [平均工资] [年龄段]




但是,要求用 Linq 来写, 谁能给出 Linq 语句,

------解决方案--------------------
C# code

var q = (from a in list
                    group a by new { range = a.age < 20 ? "<20" : (a.age >= 20 && a.age <= 30 ? "20-30" : ">30") } into g
                    select new {
                        key = g.Key,
                        count = g.Count(),
                        salary = g.Average(b=>b.salary)
                        
                    });
            foreach (var item in q)
            {
                Response.Write(item.count+"           "+item.salary+"              "+item.key.range+" <br />");
            }

------解决方案--------------------
group a by new { range = a.age < 20 ? "<20" : (a.age >= 20 && a.age <= 30 ? "20-30" : ">30") } into g
=========
 group a by new { range = a.age < 20 ? "<20" : (a.age >= 20 && a.age <= 30 )? "20-30" : ">30" } into g

http://blog.csdn.net/q107770540/article/details/6270693