实体框架组由条件组成

时间:2015-03-18 13:37:26

标签: c# asp.net linq entity-framework

我有以下查询

var maListe = (from p in db.exclure
               where (p.type.Contains("Object"))
               group p by p.libelle into g
               select new
               {
                    libellex = g.Key
               }).ToList();

我需要为要分组的元素制定条件,例如

if(x==0) group by p.libelle
else if (x==1) group by p.name
else  group by p.adresse

有没有办法在我的linq查询中正确执行?

2 个答案:

答案 0 :(得分:1)

假设已经设置了x,请尝试:

var maListe = (from p in db.exclure
                where (p.type.Contains("Object"))
                group p by new {obj = x==0 ? p.libelle : x==1 ? p.name : p.adresse } into g
                select new
                {
                    libellex = g.Key
                }).ToList();

<强>更新 排序条件需要一个属性名称以避免错误Invalid anonymous type member declarator.所以我修改了行group p by new {obj = x==0 ? p.libelle :.... etc

答案 1 :(得分:0)

此外,您可以通过以下方式创建一个lambda表达式,以用作组中的键选择器:

int x=1;
Func<Exclure,object> func = (b) =>
{
   switch (x)
   {
     case  0:
       return b.libelle;
     case  1:
       return b.name;
     default:
       return b.adresse;
   }
};
var maListe = db.exclure.Where(p=>p.type.Contains("Object")).GroupBy(func).Select(g=>g.Key).ToList();