2008-11-05 78 views
2

我有一个C#类返回一个列表,使用System.Collections.Generic列表不是F#名单System.Collections.Generic列表和F#

我想重复好像列表中找到对象或无法找到它。这是我如何在C#中完成的。

#light 
open System.Collections.Generic 

let genList = new List<int>() 

genList.Add(1) 
genList.Add(2) 
genList.Add(3) 


for x in genList do 
    printf "%d" x 

回答

3

的迭代整数通用列表,请参阅下面的例子:

for caseObj in CaseList do 
    if caseObj.CaseId = "" then 
    ... 
    else 
    ... 
+0

我是新来的F#。什么是#light(您的示例中的第一行)? – octopusgrabbus 2016-07-25 18:32:54

2

那种名单也是一个IEnumerable,所以你仍然可以使用F#的for elt in list do符号:我将如何在F#中完成类似的事情

foreach (AperioCaseObj caseObj in CaseList) 
{ 
    if (caseObj.CaseId == "") 
    {  
    } 
    else 
    { 
    } 
} 
7
match Seq.tryfind ((=) "") caseList with 
     None -> print_string "didn't find it" 
    | Some s -> printfn "found it: %s" s 
0

使用tryfind来匹配字段中记录:

type foo = { 
    id : int; 
    value : string; 
} 

let foos = [{id=1; value="one"}; {id=2; value="two"}; {id=3; value="three"} ] 

// This will return Some foo 
List.tryfind (fun f -> f.id = 2) foos 

// This will return None 
List.tryfind (fun f -> f.id = 4) foos 
3

C#列表在F#中称为ResizeArray。要在ResizeArray中查找元素,您可以使用“tryfind”或“find”。 TryFind返回一个选项类型(Option),这意味着如果找不到该元素,您将得到None。在另一方面查找抛出一个异常,如果它没有找到的元素,您正在寻找


let foo() = 
    match CaseList |> ResizeArray.tryfind (fun x -> x.caseObj = "imlookingforyou") with 
    |None -> print-string ""notfound 
    |Some(case) -> printfn "found %s" case 

let foo() 
    try 
     let case = ResizeArray.find (fun x -> x.caseObj = "imlookingforyou") 
     printfn "found %s" case 

    with 
    | _ -> print_string "not found"