2008-11-05 46 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"