System.Collections.Generic List和F#
我有一个C#类,它返回一个列表,使用System.Collections.Generic List而不是F#List 我想遍历列表以查找对象,或者不查找对象。下面是我在C#中的做法。我如何在F中完成类似的事情#System.Collections.Generic List和F#,f#,F#,我有一个C#类,它返回一个列表,使用System.Collections.Generic List而不是F#List 我想遍历列表以查找对象,或者不查找对象。下面是我在C#中的做法。我如何在F中完成类似的事情# 有关迭代整数通用列表的信息,请参见此示例: #light open System.Collections.Generic let genList = new List<int>() genList.Add(1) genList.Add(2) genList.Add(3)
有关迭代整数通用列表的信息,请参见此示例:
#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
#灯
open System.Collections.Generic
让genList=newlist()
genList.Add(1)
genList.Add(2)
genList.Add(3)
对于genList中的x
printf“%d”x
这种列表也是一个IEnumerable,因此您仍然可以在列表do中使用F#的表示elt
符号:
for caseObj in CaseList do
if caseObj.CaseId = "" then
...
else
...
使用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
C列表在F中称为ResizeArray。要在ResizeArray中查找元素,可以使用“tryfind”或“find”。TryFind返回一个选项类型(option),这意味着如果找不到该元素,则不会得到任何选项。另一方面,“查找”如果找不到要查找的元素,则会引发异常
或
我是F#的新手。光(你例子中的第一行)是用来做什么的?
match Seq.tryfind ((=) "") caseList with
None -> print_string "didn't find it"
| Some s -> printfn "found it: %s" s
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
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"