Hello group,

If I want to filter System.Collections.ObjectModel.Collection<T>, can somebody give me a code snippet as sample?

Thanks.

How about standard

1
2
3
4
 

let result = Seq.cast collection |> Seq.filter (fun item -> "<your condition goes here>") 
By on 4/13/2009 11:19 AM ()

How about standard

1
2
3
4
 

let result = Seq.cast collection |> Seq.filter (fun item -> "<your condition goes here>") 

That works, too :-) But, one may still need to convert the resulting seq<'a> back to a Collection.

By on 4/13/2009 11:36 AM ()

That works, too :-) But, one may still need to convert the resulting seq<'a> back to a Collection.

I see your point...

By on 4/13/2009 4:25 PM ()

Maybe I'm just being dense. But,

1
Collection T

is a Seq because it implements

1
IEnumerable T  

( I can't get angle brackets to work. )

[link:msdn.microsoft.com]

So, this works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
open System.Collections.ObjectModel

let coll = new Collection int () // note that this should have greater than and less than around int

coll.Add(1);

coll.Add(2);

coll.Add(3);

coll.Add(4);

coll.Add(5);

let newColl = coll |> Seq.filter (fun a -> a % 2 = 0 )

newColl |> Seq.iter (fun a -> printfn "%d" a)

System.Console.ReadKey() |> ignore

As an aside does anyone know how to prevent the BB from eating gt and lt?

By on 4/13/2009 5:57 PM ()

I'm pretty sure there is something built-in, but here is a simple solution:

1
2
3
4
5
let filter f (xs:System.Collections.ObjectModel.Collection<'a>) =
    let xs' = new System.Collections.ObjectModel.Collection<'a>()
    for x in xs do
        if f x then xs'.Add(x)
    xs'

To help convert between F# sequences and Collections, give these a try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type System.Collections.ObjectModel.Collection<'a>
    with
        static member of_seq xs =
            let xs' = new System.Collections.ObjectModel.Collection<'a>()
            xs |> Seq.iter xs'.Add
            xs'

module Seq =
    let of_coll xs = seq { for x in xs -> x }


let xs = [1;2;3;4] |> System.Collections.ObjectModel.Collection<_>.of_seq

let ys = xs |> filter (fun x -> x > 2)
By on 4/13/2009 11:04 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper