Object structure
A class has multiple lists of data.
Class
List1 of double
List2 of double
List3 of double
List4 of double
Objective: Sort multiple lists based on one list. E.g. List1 in ascending order and all other lists to follow that order to maintain individual point relativity based on index.
Initial implementations that I have tried are:
List2, 3 and 4 with List 1 and then sort based on List 1. Then combine sorted lists again.e.g.
var x1 = testData.SelectMany(d => d.xData).ToList();
var y1 = modelData.SelectMany(d => d.yData).ToList();
var y2 = modelData.SelectMany(d => d.y2Data).ToList();
var sampleValues = x1.Zip(y1, (x, y) => new { X = x, Y = y }).OrderBy(v => v.X);
var sampleValues1 = x1.Zip(y2, (x, y) => new { X = x, Y2 = y }).OrderBy(v => v.X);`
//Next select X, Y from sampleValues and select Y2 from sampleValue2
SelectMany on different lists and then put that into an anonymous type. SelectMany does not work with this as it needs definite data type to return.Anything that I am missing in these approaches or there is another approach required to get what I am trying to achieve.
Also having a class with all this data or lists as individual rows and data inside columns is not an option for me. This is because I have a list of objects having these properties. So eventually I want to merge list data across objects sampleData lists and then sort and use that data.
Feel free to let me know in case further information is required.
There's a not well-known method Array.Sort that sorts an array according to the order of a second array. I made a small extension method that utilizes this oldie:
public static class ICollectionExtensions
{
public static IEnumerable<TSource> SortLike<TSource,TKey>(this ICollection<TSource> source,
IEnumerable<TKey> sortOrder)
{
var cloned = sortOrder.ToArray();
var sourceArr = source.ToArray();
Array.Sort(cloned, sourceArr);
return sourceArr;
}
}
You can use this by calling ...
var list21 = list2.SortLike(list1);
The advantage of this method is that it's extremely fast, despite the two ToArray() calls in it. ToArray() creates a shallow copy of the collection, which only takes a couple of milliseconds with a list of 10 million items. Array.Sort is fast because it selects the best sorting algorithm for the size of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With