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.


It assumes ASCII character format where to convert from lowercase to uppercase you subtract 32 from the original ASCII value. This is because the ASCII values for uppercase are smaller than those for lower case and it's a constant difference between A and a, B and b and so on.

For reference: http://www.asciitable.com/

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

次のようなものを使用できます。

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

これにより、 の ID の順序に従って並べ替えられますsortOrderIdsFooID が見つからないオブジェクトは、結果リストの一番上に表示されます。

それらを一番下にしたい場合は、次のようにコードを変更します。

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