通过结果将LINQ组直接转换为模型

时间:2017-02-10 18:03:34

标签: c# linq

我想将LINQ查询的结果直接存储到我的模型中,但我只能通过将其存储到变量中来实现它。

var mdl = (from age in dy.vwFacetPool
                       group age by new { age.AgeGroup, age.AgeString }
                      into grp
                       select new { a = grp.Key.AgeGroup, b = grp.Key.AgeString, c = grp.Count() }).ToList();

但我想先将它存储到模型而不是变量中。

我有模特

  public class AgeGroupCounts
{
    public int AgeGroup { get; set; }
    public string AgeValue { get; set; }
    public int AgeCount { get; set; }
}

然后

public class NewEmail
{
    public NewEmail()
    {
        this.Newz = new News();
        //this.Age = new AgeGroupCounts();
        this.AgeGroup = new List<AgeGroupCounts>();
    }

    public News Newz { get; set; }
    //public AgeGroupCounts Age { get; set; }
    public List<AgeGroupCounts> AgeGroup { get; set; }
}

所以我想将选择中的3个输出字段映射到模型字段,但此时丢失了

 model.AgeGroup = (from age in dy.vwFacetPool
                       group age by new { age.AgeGroup, age.AgeString }
                      into grp
                       select new { grp.Key.AgeGroup, grp.Key.AgeString, grp.Count() }).ToList();

我知道我可以将它存储到var和模型中,但这似乎是我做错了方法!

3 个答案:

答案 0 :(得分:2)

如果您选择AgeGroupCounts而不是匿名类型,则会从LINQ查询中返回List<AgeGroupCounts>

model.AgeGroup = (from age in dy.vwFacetPool
                   group age by new { age.AgeGroup, age.AgeString }
                  into grp
                   select new AgeGroupCounts { AgeGroup = grp.Key.AgeGroup, AgeValue = grp.Key.AgeString, AgeCount = grp.Count() }).ToList();

答案 1 :(得分:0)

我认为您的select语句不应该是匿名类型......

 select new { grp.Key.AgeGroup, grp.Key.AgeString, grp.Count()...

尝试将其更改为

 select new AgeGroupCounts() { ... }

答案 2 :(得分:0)

这是你在找什么?

var mdl = (from age in dy.vwFacetPool
    group age by new { age.AgeGroup, age.AgeString }
    into grp
    select new AgeGroupCounts {
        AgeGroup = grp.Key.AgeGroup, 
        AgeValue = grp.Key.AgeString, 
        AgeCount = grp.Count()
    }).ToList();