如何将查询结果分配给整数数组

本文关键字:整数 数组 分配 结果 查询 | 更新日期: 2023-09-27 18:27:35

public List<Workflow> GetMyWorkflows(int[] MyRoles)
        {
            int[] myWorkflowIDs = new int[] { };
            RapidWorkflowDataContext context = new RapidWorkflowDataContext();
                var query = from w in context.WorkflowRoles
                            where MyRoles.Contains((int)w.RoleID)
                            select w.WorkflowID;
                var distinctWorkflows = query.Distinct();
                myWorkflowIDs = distinctWorkflows.toArray();
                return myWorkflowIDs;
        }

在此方法中,我想检索用户可以检索的工作流数组访问。我收到以下错误:无法隐式转换类型'int?[]' 到 'int[]'

如何将查询结果分配给整数数组

我想检索工作流数组

但是您的方法必须返回 List<Workflow>List<int>

所以你应该跳过数组的想法。另一个问题是在intint?之间。您可以在带有 select w.WorkflowID.Valueselect w.WorkflowID ?? 0 的选择子句中解决这个问题。或者干脆select w List<Workflow>.

此外,最好在上下文变得无法访问时对其进行处置。

    public List<int> GetMyWorkflows(int[] MyRoles)
    {
        using (RapidWorkflowDataContext context = new RapidWorkflowDataContext())
        {
           var query = from w in context.WorkflowRoles
                    where MyRoles.Contains((int)w.RoleID)
                    select w.WorkflowID ?? 0;
                    // select w;  to return a List<WorkFlow>
           var distinctWorkflows = query.Distinct();
           return distinctWorkflows.ToList();   // ToList because we are closing the Context
        }
    }

我猜工作流ID的类型是int?。如果确定它不能为 null,请将中心查询更改为:

var query = from w in context.WorkflowRoles
                        where MyRoles.Contains((int)w.RoleID)
                        select w.WorkflowID.Value;

这将确保query现在属于IEnumerable<int>类型而不是IEnumerable<int?>int通过Distinct()ToArray()函数紧随其后。

这对我来说似乎是一个很好的错误

Cannot convert type 'int?[]' to 'int[]'

您必须有一个类型 int? 的数组,并尝试将其隐式转换为 int

因此,您有两种选择 - 停止尝试隐式转换,并允许int?[]结果,如下所示:

int?[] myWorkflowIDs = new int?[] { };

或强制进行转换,如下所示:

RapidWorkflowDataContext context = new RapidWorkflowDataContext();
var query = from w in context.WorkflowRoles
        where MyRoles.Contains((int)w.RoleID)
        select (int)w.WorkflowID;
        // or w.WorkflowID ?? 0; as necessary
所以

int?也可以写Nullable<int>它基本上是一个可以接受null值的整数。例如:

int? nullableNumber = 5;   // Set to a value
nullableNumber = null?     // Set to null (which is possible because int? is nullable).

可以想象,Nullable<int> 对数据库很有用,因为有时您可能有一个具有 null 值的列,因此此类型提供了映射到此类值的有用方法。但问题是,在你的代码中,你必须处理两种不同的类型,intint? .可以使用以下命令在两个值之间进行强制转换:

// If the nullable-integer is not-null then use it's value, else default to `0`.
int nonNullable = nullableNumber ?? 0; 

如果值为 null,则将用 0 替换 null。或者,您可以将myWorkflowIDs存储在可为空的值(Nullable<int>[]int?[](中,这在语义上更好地反映了数据库中的列值实际上是什么。