0

I currently have a method which uses .Select to extra all of the properties from each object in a collection into an array. Then, I do something to it which results in the array being re-ordered. I then am trying to figure out how to return an ordered list of the original objects, based on the order of each of those objects properties. I suspect that there may be a solution using LINQ which I'd like to use, but can't quite figure it out.

Worst case scenario and I'd simply not create the array of Bar in the example below and only refer to the original collection, but I'd like to not have to reference said Foo collection so frequently.

public class X
{
    public IEnumerable<Foo> Foos { get; set; }
    public IOrderedEnumerable<Foo> OrderTheFoos()
    {
        Bar[] allBars = Foos.Select(x => x.MyBar).ToArray();
        allBars = allBars.OrderBy(x => new Random().Next()).ToArray();
        return // return a list of Foos based on the order of the array of Bars
    }
}

public class Foo
{
    public Foo(string name) 
    { 
        MyBar = new Bar(); 
        Name = name; 
    }
    public string Name { get; set; }
    public Bar MyBar { get; set; } 
}

public class Bar { }
Danny Goodall
  • 798
  • 1
  • 9
  • 33
  • _OrderBy Random_? Perhaps you meant to perform a Knuth / Fisher-Yates Shuffle? See [Randomize a List](https://stackoverflow.com/questions/273313/randomize-a-listt) – Wyck Aug 02 '22 at 15:17
  • Your question also sounds like you just want to [Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – Wyck Aug 02 '22 at 15:19
  • Your question also sounds like you are trying to sort an `IEnumerable` without first transforming it to a sortable collection -- spoiler: you can't. Even `IEnumerable.OrderBy` [internally](https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs#L2543-L2551) puts things into a collection to sort them. See [How to sort an IEnumerable](https://stackoverflow.com/questions/3630687/how-to-sort-an-ienumerablestring) – Wyck Aug 02 '22 at 15:25

0 Answers0