2011-04-12 43 views
0

在下面的代码片段中,我试图提取包含在形成代词键的嵌套元组中的recid。 嵌套元组格式(的Int32,(布尔,布尔)) -演员/转换问题

我要寻找的项目的Int32的值(这是 实际上是一个数据库记录行ID)。

在下面的匹配代码中,我试图将recid添加到列表中,但首先我将对象转换为整数。
但是,这会产生以下错误 - 不知道为什么?

错误: 从类型此运行时胁迫或类型的测试“一个为int32
涉及基于之前该程序点信息的不确定的类型。 某些类型不允许运行时类型测试。需要进一步的类型注释。 这里被引用的字典定义为:

// Create Dict 
let rdict = new Dictionary<_,_>() 
// Add elements 
rdict.Add((x.["PatientID"],(true,true)),ldiff) 

// Extract Dict items 
let reclist = new ResizeArray<int32>() 
for KeyValue(k,v) in rdict do 
match k with 
    | ((recid,(true,true)) -> 
    printfn "Found a matching Record: %A " recid; // <- prints correct result 
    let n = (recid:?> int32)       // <- coercion error 
     reclist.Add(n) 
+0

线'rdict.Add((X [ “PatientID”],(真,真))'具有开闭括号的错配数。哪些'Dictionary'的键和值类型?是'int *(bool * bool)'只能用作键类型,还是'int'键类型和'bool * bool'的值类型?另外,x的实际类型是什么? “PatientID”]'?是否返回一个'int'或一个盒装的'int'(即'obj'可以被转换为'int')? – ildjarn 2011-04-12 23:18:28

+0

糟糕 - 我在发布rdict.add行时疯狂 - 现在更正了(我实际上是/构建了一个行/列对作为字典值的列表,dict键实际上是一个组合(rid,(boolean,boolean))值(布尔值定义rec是否存在于一对表格)x。[“PatientID”]是一个从数据库表中检索到的(未装箱的)int值。 – BrendanC 2011-04-12 23:29:27

+0

实际上,一个m矿问题 - 如果你的伴随“布尔”对是“真实的”,而不是任何其他组合,你是否打算只将ID从'rdict'复制到'reclist'? – ildjarn 2011-04-12 23:36:07

回答

1

假设rdictDictionary<int*(bool*bool), _>然后产生ResizeArray<int>我建议:

let reclist = 
    (ResizeArray<_>(), rdict.Keys) 
    ||> Seq.fold(fun list (id,_) -> list.Add id; list) 

此外,Dictionary<int*(bool*bool), _>令我奇怪的。为什么不是Dictionary<int*bool*bool, _>?也就是说,为什么要把这对bool作为第二个元组?如果你把这个变化,一会又打电话rdict.Add像这样:

rdict.Add ((x.["PatientID"], true, true), ldiff) 

而且reclist将改为:

let reclist = 
    (ResizeArray<_>(), rdict.Keys) 
    ||> Seq.fold(fun list (id,_,_) -> list.Add id; list) 

编辑:在你的评论中提到打造的愿望根据Dictionary密钥中两个bool s的不同组合,分开ResizeArray s。这里有一个想法是这样做的:

let reclistOnlyA, reclistOnlyB, reclistBoth, reclistNeither = 
    ((ResizeArray<_>(), ResizeArray<_>(), ResizeArray<_>(), ResizeArray<_>()), rdict.Keys) 
    ||> Seq.fold(fun (a, b, both, neither as lists) (id, bools) -> 
     (match bools with 
     | true, false -> a 
     | false, true -> b 
     | true, true -> both 
     | false, false -> neither).Add id 
     lists) 
+0

字典密钥从初始版本发展而来,只有recid值。从逻辑上讲,我查看布尔值与recid有些不同,所以我想我把它们放在一个单独的嵌套元组中。我可以看到你的方法有一些优势 - thx为你的帮助到目前为止。 – BrendanC 2011-04-12 23:50:05

+0

@BrendanC:效率(减少分配计数)是'int * bool * bool'超过'int *(bool * bool)'唯一的真正优势。从风格上来说,你给我的感觉很奇怪,但如果它对你有意义,我不会看到任何重大的伤害。 : - ] – ildjarn 2011-04-12 23:52:26

0

为了完整性和未来的参考,我只是想根据进一步的测试发布我的结果。 通过装箱/拆箱,我能够成功修改我以前发布的代码。

希望这将有一些用于未来的其他人。

// Add initial value note the box call here 
diff_dict.Add((box x.["PatientID"],(true,true)),ldiff) 


let reclist = new ResizeArray<int32>() 
for KeyValue(k,v) in rdict do 
    //printfn "Difference Dictionary - Key: %A; Value: %A; " k v 
    match k with 
     // extract the result - note the 'unbox' call 
     | (recid,(true,false)) -> let n:int32 = unbox recid 
            reclist.Add(n)