ceds
ceds

Reputation: 2185

C# Collection of Lists - Sorting

I'm looking for an efficient way to "link" arrays/lists to each other and sort all of the lists/arrays synchronously based on one of the arrays.

For example lets say I have three lists:

List<double> Data1;
List<double> Data2;
List<double> Data3;

The items inside the lists are obviously not structurally related, but I want them to be. For instance Data1[0], Data2[0] and Data3[0] are related.

So now I want to sort the collection of the three lists based on Data1 from largest to smallest. How can I do this so that all three lists stay synchronised?

Thank you in advance for your help!

Upvotes: 1

Views: 462

Answers (3)

Douglas
Douglas

Reputation: 54877

I would create a list of an anonymous type that combines the values from all three respective lists together, sort based on the field you want, and then project the sorted values back into their respective lists:

var combined =
    Enumerable.Range(0, Data1.Count)
              .Select(i => new
              {
                  Item1 = Data1[i],
                  Item2 = Data2[i],
                  Item3 = Data3[i],
              })
              .OrderBy(c => c.Item1)
              .ToList();

Data1 = combined.Select(c => c.Item1).ToList();
Data2 = combined.Select(c => c.Item2).ToList();
Data3 = combined.Select(c => c.Item3).ToList();

Upvotes: 1

Guffa
Guffa

Reputation: 700272

Make the items structurally related:

public class Data {
  public double Data1 { get; set; }
  public double Data2 { get; set; }
  public double Data3 { get; set; }
}

Having a List<Data>, you can easily sort the items on one of the properties:

theList.Sort((x, y) => x.Data2.CompareTo(y.Data2));

Upvotes: 5

Dave Bish
Dave Bish

Reputation: 19646

You can use Zip to tie the arrays together, and then use the projected type to order by a particular point:

List<double> Data1;
List<double> Data2;
List<double> Data3;

var orderedByDataOne = Data1
    .Zip(Data2, (one, two) => new {one, two})
    .Zip(Data3, (zipped, three) => new {zipped.one, zipped.two, three})
    .OrderBy(x => x.one)

Upvotes: 1

Related Questions