简体   繁体   中英

Query results to new table object in F#

Short question.

I have just recently performed my first successful query in F#. I now want to be able to refer to the results and perform various computations on it. If I just assign the query to an object, "newData," it does not let me refer to the elements of this new data table (eg newData.Billed_Amount).

Is there a quick function like ToList() to make it so that I can work with this new data?

Here is some sample code:

let dc = new TypedDataContext()

let newData = query { for x in dc.MyData do
                      where (x.ID = "number of type string")
                      groupBy x.Code into g
                      let average = query { for x in g do
                                            averageBy x.Billed_Amt }
                      select (g, average) }

System.Console.WriteLine(newData)

I now want to, for example, calculate standard deviation within all the groups, but I noticed I cannot perform this computation within a query. This is where I would like to have the query results referable to work with.

Thanks!

Because IQueryable inherits from IEnumerable , you can use functions in the Seq module such as toList and toArray .

open System.Linq //for AsQueryable extension method

let q s =
  query {
    for x in s do
    where (x > 1)
    select x
  }

q ([1; 2].AsQueryable()) |> Seq.toList //[2]

Just do this:

newData |> Seq.toList

The pipe operator |> applies the function on the right to the value on the left. You could put it into newData if you want it to be a list:

let newData = query { for x in dc.MyData do
                      ...
                      select (g, average) }
              |> Seq.toList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM