2

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));
4

2 回答 2

4

您可以使用List.IndexOf

var ordered = listOfFoo.OrderBy(o => sortOrderIDs.IndexOf(o.Id));

编辑:因为sortOrderIDs是一个数组:

var ordered = listOfFoo.OrderBy(o => Array.IndexOf(sortOrderIds, o.Id));

或者,如果您想对列表和数组使用相同的内容,请将其转换为IList

var ordered = listOfFoo.OrderBy(o => ((IList)sortOrderIds).IndexOf(o.Id));
于 2013-01-24T22:13:45.503 回答
3

You could use something like this:

var ordered = listOfFoo.OrderBy(x => Array.IndexOf(sortOrderIds, x.Id));

This would sort them according to the order of the IDs in sortOrderIds. Foo objects whose IDs are not found will be at the very top of the resulting list.

If you want them to be at the bottom, change the code like this:

var ordered = listOfFoo.OrderBy(x => 
                                {
                                    var idx = Array.IndexOf(sortOrderIds, x.Id);
                                    return idx == -1 ? int.MaxValue : idx;
                                });
于 2013-01-24T22:14:11.203 回答