无法将类型'Anonymous Type#1 []'隐式转换为'int []'

时间:2015-10-13 10:59:14

标签: c# entity-framework linq asp.net-mvc-4 anonymous-types

我有以下情况,我尝试使用分组方法

获取数据库详细信息
  //Gets MulitCourseIds from db of selected CourseIds 
        int[] _hasListCourseIds = (from mcd in _db.MultiCourseDetails
                                 where _lstCourseIds.Contains(mcd.CourseId.Value)
                                 group mcd.MultiCourseId by mcd.MultiCourseId into g
                                 select new { multiCourseId = g.Key }).ToArray();
                                   ************  error is occuring here**********

        if (_hasListCourseIds.Count > 0)
        {
            //Checks the count of courseIds from the db and selected courseIds
            foreach (var _multiCourseId in _hasListCourseIds)
            {                  
                var _courseCount = _db.MultiCourseDetails                                       
                                    .Where(x => x.MultiCourseId == _multiCourseId )
                                    .Count();
                if (_courseCount == _lstCourseIds.Count)
                {
                    return true;
                }
            }

我收到错误

  

无法将类型'Anonymous Type#1 []'隐式转换为'int []'

还邀请任何改进代码的建议。

1 个答案:

答案 0 :(得分:2)

问题是您正在投射anonymous类型,但将其分配给int数组。由于您只投影一个属性,因此您不需要匿名类型: -

  int[] _hasListCourseIds = (from mcd in _db.MultiCourseDetails
                             where _lstCourseIds.Contains(mcd.CourseId.Value)
                             group mcd.MultiCourseId by mcd.MultiCourseId into g
                             select g.Key).ToArray();

我认为MultiCourseIdint