c# - 如何在 C# 中获取字典值集合的计数

标签 c# linq asp.net-mvc-4 generics data-structures

我正在尝试获取字典值集合的计数,其中集合项的字段与集合中的键以及类型相匹配。

所以我的集合看起来像这样,注意对象已初始化,这只是伪代码:

var results = Dictionary<string, List<CourseEnrollmentsByStudentSQLResult>();

现在,CourseEnrollmentsByStudentSQLResult 是一个数据传输对象,它映射到从我的查询返回的行。

public class CourseEnrollmentsByStudentSQLResult
{
    public int StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string College { get; set; }
    public int CollegeId { get; set; }
    public string Prefix { get; set; }
    public string CourseNumber { get; set; }
    public string Course { get; set; }
    public int CourseId { get; set; } 
    public string Program { get; set; }
    public string Term { get; set; }
    public string Status { get; set; }
    public List<StudentCoursesSQLResult> Courses { get; set; }
}

您会注意到我的 CourseEnrollmentsByStudentSQLResult 类也有一个 StudentCoursesSQLResult 对象的集合。这是我试图根据两个条件进行计数的列表。

首先,类(class)(字典中的字符串 KEY)与 StudentCoursesSQLResult 的类(class)相匹配,然后我需要对 StudentCoursesSQLResult.Type 进行过滤。

这是StudentCoursesSQLResult类:

public class StudentCoursesSQLResult
{
    public int StudentID { get; set; }
    public int Position { get; set; }
    public string Prefix { get; set; }
    public string CourseNumber { get; set; }
    public string Course { get; set; }
    public string Type { get; set; }
}

现在为了获取计数,我正在循环遍历字典并输出每个键的 header ,这就是我尝试输出字典值集合的计数的地方。

    foreach(var result in results) {
       <span class="label label-default label-fat">
          @result.Value.SelectMany(r => r.Courses).Count(c => c.Course == result.Key && c.Type == "required")
       </span>
    }

但由于某种原因它返回零,而我知道它不应该返回零。

有人可以给我指出正确的方向吗?到目前为止,我在网上找到的所有内容都说要使用 SelectMany,但我没有任何运气。

这是字典值集合的单个类(class)的调试输出的屏幕截图,其中类型为“必需”。

enter image description here

最佳答案

查看您的屏幕截图,“高级法语 I:结构与表达”“中世纪艺术与建筑”的键不匹配,这解释了错误的原因计数。

相反,将 CourseEnrollmentsByStudentSQLResult 集合过滤为与字典键匹配的类(class),然后选择这些匹配记录中的所有类(class),最后计算“必需”的类(class)。

@result.Value.Where(r => r.Course == result.Key)
             .SelectMany(r => r.Courses)
             .Count(c => c.Type == "required");

关于c# - 如何在 C# 中获取字典值集合的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29246695/

相关文章:

C# Linq select object in List where int in object child List<int> 出现 n 次

asp.net - asp .net mvc 4 下拉列表

javascript - 从 .js 文件调用内部 Javascript 函数

javascript - 在 C# 中上传时在图像上添加日期

c# - Azure 应用服务容器上的 ASP.net core docker https

c# - 由 C# EF 核心调用时的暂停选择查询,MSSQL 管理工作室可以很好地执行查询。为什么?

c# - 将 datatables.js 与 asp.net gridview 集成

c# - .NET 6 OpenAPI : How to specify required properties in a POST request class?

c# - 如何对列表进行排序,将 map 从旧位置保存到新位置?

c# - 让方法语法中的查询语法?