【问题标题】:Lambda expression select Count from virtual ICollectionLambda 表达式从虚拟 ICollection 中选择计数
【发布时间】:2023-04-02 10:05:02
【问题描述】:

我在使用 lambda 表达式时遇到了问题,我有一些相关的表,我需要在这里选择一些带有计数和平均函数的结果,例如示例类

class Course{
public long id;
public string name;
public virtual ICollection<Chapter> chapters;
}

class Chapter{
public long id;
public virtual ICollection<Videos> videos;
public virtual ICollection<Files> files;
}

我需要选择它们进入

select new{
videoCount = [number of video releated to course],
fileCount = [number of file releated to course],
}

如何使用 lambda 表达式进行选择

var result = from c in Courses...
             i cant figured out here
             select new{
                          videoCount = [number of video releated to course],
                          fileCount = [number of file releated to course],
             };

感谢您的帮助。

块引用

【问题讨论】:

  • 能否也向我们展示一下您的视频和文件课程?

标签: c# asp.net asp.net-mvc entity-framework lambda


【解决方案1】:

您的代码中有一个错误:在public virtual ICollection&lt;Chapter&gt; 之后您没有属性名称。我假设它被称为章节。 视频和文件属性也是如此。

试试这个:

var result = courses.Select(c => new
{
    videoCount = c.chapters.Sum(chapter => chapter.Videos.Count()),
    fileCount = c.chapters.Sum(chapter => chapter.Files.Count())
});

Sum每章的视频数量,以获得课程总数。

【讨论】:

    【解决方案2】:

    试试这个:

    var courses = new List<Course>();
    
    courses.Select(x=> new { 
                           VideoCount = x.Chapters.Sum(v=>v.Videos.Count),
                           FilesCount = x.Chapters.Sum(v=>v.Files.Count)
                           });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多