Feed current item to next item in LINQ query

I have a set of elements that I want to convert (basically, wrap metadata). For the first item in the collection, I just wrap the necessary metadata around the item, and you're done. The metadata of the second element depends on the metadata of the previous element, so I want to pass the metadata of the first element to the second element.

Following....

object[] A; A.skip(1) .Zip( A, (first, second), a => new Metadata( first, second ) ); 

... will not work because it uses object as a second input, not Metadata . This is true for any other solution I've seen so far (passing the original object, not the result of the Select() function).

How can I pass the result of Select() for the first element in my LINQ query to Select() for the second element?

I know I could use a for loop to accomplish this, but I'm wondering if there is a more functional way to solve this problem. There must be a solution in functional style languages ​​like F #, and I wonder if I can translate this into a LINQ solution in C #. A single line solution would be especially useful.

By linking metadata together in this way, I can transfer important information from one element to all of the following elements, such as flags or context. The goal, ultimately, is not only to know about the previous element, but also in the entire context of the current element. The current item can then change context for all of the following items, etc.

+1
source share
2 answers

This behavior is usually performed using scan or a similar function in functional programming languages. In F # you can do it like this:

 originalSequence |> Seq.scan (fun (prev, current) -> Some <| new Metadata( (* ... stuff ... *) )) None 

See this question for an implementation of the scan extension method in C #. Given this method, you can implement your request as follows:

 A.Scan((previous, current) => new Metadata(/* ... */), null) 

It is impossible to imagine an elegant single-line implementation of the scan method.

+1
source

Try .Aggregate() .

 var data = A.Aggregate(new Metadata(null, A), (meta, a) => new Metadata(meta, a)); 

I cannot guarantee that I have syntax for this right, especially for your code. However, the idea should be clear, and if you are editing a more detailed example, I can extend this.

+1
source

Source: https://habr.com/ru/post/948222/


All Articles