linq查询中某些字段的计数

时间:2017-10-23 15:46:06

标签: c# linq

这是我的查询,它工作正常并给我预期的结果;

var result2 = (from dt in disMudahaleTipiRepo
               join dm in disMudahaleRepo on dt.Kodu equals dm.MudahaleKodu
               join kr in kurumRepo on dm.CreatedKurumKodu equals kr.KurumKodu
               join yu in userRepo on dm.CreatedBy equals yu.ID
               group dt by new {  yu.Ad, yu.Soyad, kr.KurumAdi } into grp
               select new
               {
                   AdSoyAd = grp.Key.Ad + " " + grp.Key.Soyad,
                   KurumAdi = grp.Key.KurumAdi,
                   KoduSayisi1 = grp.Select(s => s.Kodu).Where(w=>w== "401.030").Count(),
                   KoduSayisi2 = grp.Select(s => s.Kodu).Where(w=>w== "402.090").Count(),
                   KoduSayisi3 = grp.Select(s => s.Kodu).Where(w=>w== "406.020").Count(),
                   KoduSayisi4 = grp.Select(s => s.Kodu).Where(w=>w== "402.020").Count(),
                   KoduSayisi5 = grp.Select(s => s.Kodu).Where(w=>w== "406.070").Count()
                   ...
               });

唯一的问题是有86个字段(lol),所以它最终会像那样:

               ...
               select new
               {
                   AdSoyAd = grp.Key.Ad + " " + grp.Key.Soyad,
                   KurumAdi = grp.Key.KurumAdi,
                   KoduSayisi1 = grp.Select(s => s.Kodu).Where(w=>w== "401.030").Count(),
                   ...
                   KoduSayisi91 = grp.Select(s => s.Kodu).Where(w=>w== "436.070").Count()

               });

我没有这样做,而是尝试创建一个字典并保持(Code,Number)在理论上的优点,但我怎么能告诉它linq?

我不认为实体的定义是必要的,但让我分享一下;

public class DisMudahaleTipi : Entity
{
    public string Kodu { get; set; }
    public string Name { get; set; }
}
public class DisMudahale : AuditableEntity
{
    public string MudahaleKodu { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用子查询,但我手边没有数据库来测试以下是否有效:

var keys = ["401.300", .. ];
var result = (from dt in disMudahaleTipiRepo
 join dm in disMudahaleRepo on dt.Kodu equals dm.MudahaleKodu
 join kr in kurumRepo on dm.CreatedKurumKodu equals kr.KurumKodu
 join yu in userRepo on dm.CreatedBy equals yu.ID
 group dt by new {  yu.Ad, yu.Soyad, kr.KurumAdi } into grp
 select new
 {
    AdSoyAd = grp.Key.Ad + " " + grp.Key.Soyad,
    KurumAdi = grp.Key.KurumAdi,
    Kudos = (from key in keys
             select new 
             {
                Key = key,
                Amount = grp.Count(w => w.Kudo == key)
             }).ToList(),
}).ToList();

注意:除了子查询,我更改了Select(s=>s.Kudo).Where(w=>w=="...").Count()以降低Linq的复杂性并提高性能。