Given the following:
public class Foo
{
/* other properties */
public Int32 Id { get; set; }
}
var listOfFoo = new[]{
new Foo { Id = 1 },
new Foo { Id = 2 },
new Foo { Id = 3 }
};
var sortOrderIds = new[]{
2, 3, 1
};
If I wanted to sort listOfFoo to have the Ids end up in the same order as presented in sortOrderIds, what's the best way? I assume I could sort using something like:
Int32 SortUsingIdArrayAsReference(Foo x, Foo y)
{
// creative license on "IndexOf", bear with me
return Int32.CompareTo(sortOrderids.IndexOf(x.Id), sortOrderIds.indexOf(y.Id));
}
But is that really the best way to do this? I was hoping LINQ may have something better I could use, but if not oh well. Just looking for other input and see if anyone else has a better way.
You can use List.IndexOf
var ordered = listOfFoo.OrderBy(o => sortOrderIDs.IndexOf(o.Id));
Edit: Since sortOrderIDs is an array:
var ordered = listOfFoo.OrderBy(o => Array.IndexOf(sortOrderIds, o.Id));
Or, if you want to use the same for lists and arrays, cast it to IList:
var ordered = listOfFoo.OrderBy(o => ((IList)sortOrderIds).IndexOf(o.Id));
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