Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort IEnumerable<Object> by property and ordered array of those properties

Tags:

c#

sorting

linq

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.

like image 922
Brad Christie Avatar asked Dec 20 '25 02:12

Brad Christie


1 Answers

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));
like image 118
Tim Schmelter Avatar answered Dec 21 '25 18:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!