JamesHoux
JamesHoux

Reputation: 3447

How can I use LINQ with a class that has parallel arrays?

I've recently started wanting to leverage LINQ in my code. I'm working with a TimeSeries class that looks like this:

public struct TimeSeriesFloat
{
    public DateTime[] DateTime;
    public float[] Value;
}

I want to be able to use LINQ to sort on "Value" and have the DateTime array also get sorted in a way that maintains the 1:1 mapping between DateTime[i] and Value[i].

I attempted to implement an IEnumerator on the class to start, but I couldn't even get that to work without errors. So then I stepped back and asked myself if it's even worth doing because it might not be possible to make sorting on one array also sort the other array in an parallel way that maintains the mapping.

Is it possible?

EDIT: WOOPS! My apologies. In my haste I was calling it a class. It's a struct. :)

Upvotes: 3

Views: 76

Answers (1)

Cetin Basoz
Cetin Basoz

Reputation: 23797

As mentioned in comments, I would instead a TimeSeries class that holds a DateTime and a float:

public struct TimeSeries
{
  public DateTime DateTime;
  public float Value;
}

Then you would have a collection of these (be it an array, list, whatever IEnumerable) that you could do all sort of Linq operations on. (That is also data you get from a database looks like, struct modeling a single row with members as columns).

If for whatever reason you have to start with the struct you have, then you could make it into an IEnumerable like this:

var tsf = timeSeriesFloat.DateTime
    .Zip(tsf.Value, (f, s) => new {DateTime=f,Value=s});

This would create an IEnumerable. You can then say sort on Value:

var sortedByValue = tsf.OrderBy( x => x.Value);

and you can do other sorts of Linq operations on it, and if you like you can create a new TimeSeriesFloat with your sorted (filtered, ...) data.

Upvotes: 4

Related Questions