0

並べ替えのソースとして配列を使用して、インデックスでリストを並べ替えるのに問題があります。

私のクラスに5つのレコードが設定されていると仮定します

class Program
{
    static void Main(string[] args)
    {
     int[] myInt {2,1,0,3,4}
     List<Tests> myTests = new List<Tests>; 

     //this part doesn't work

     for (int i = 0; i < 4; i++)
        {
         myInt[i] = myTests[i];
         }
     myTests.ForEach(i => Console.WriteLine("{0} {1}", i.id, i.myString));
    }
}

私のクラスの定義

class Tests
{
     public int iD {get; set;}
     public string myString {get; set;}

     public Tests (int iD, string myString)
    {
       this.iD = iD;
       this.myString = myString
    }
{

出て欲しいもの

     record 2
     record 1
     record 0
     record 3
     record 4

リストに並べ替え関数を使ってみましたが、並べ替え条件として配列を使った例が見つからなかったので、ちょっと迷ってしまいました。私は提供された助けに感謝します。

4

4 に答える 4

2

私の頭の上から、次のようなものがうまくいくはずです:

var sortedTests = myInt
    .Select((x,index) => new {test = myTests[x], sortIndex = index})
    .OrderBy(x => x.sortIndex)
    .Select(x => x.test)
    .ToList()

うーん。実際、Linq-to-objects を使用すると、多少簡単になります。

var sortedTests = myInt
    .Select(x => myTests[x])
    .ToList();
于 2012-12-06T13:02:34.983 に答える
0

提供されたコードは漠然としているので、いくつかの異なるシナリオを作成しました。
1.インデックスに基づいて作成します。
2. インデックスに基づくソート。

それを IDE に貼り付けると、機能します。

 class Program
  {
    static void Main(string[] args)
    {
      int[] myInt = new[] { 2, 1, 0, 3, 4 };

      // there is nothing to sort at this time, but this is how I would make a new list matching your index....
      var myTests = (from x in myInt select new Tests(x, "whatever")).ToList();

      myTests.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));


      // So assuming that you are starting with an unsorted list....
      // We create and priont one....
      myTests = new List<Tests>();
      for (int i = 0; i < myInt.Length; i++)
      {
        myTests.Add(new Tests(i, "number " + i));
      }

      Console.WriteLine("unsorted ==");
      myTests.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));

      // And this will perform the sort based on your criteria.
      var sorted = (from x in myInt
                    from y in myTests
                    where y.iD == x
                    select y).ToList();

      // And output the results to prove it.
      Console.WriteLine("sorted ==");
      sorted.ForEach(i => Console.WriteLine("{0} {1}", i.iD, i.myString));

      Console.Read();
    }
  }
于 2012-12-06T13:27:47.683 に答える
0

myTests の値を別のリストに割り当てる必要があります

List<Tests> newTests = new List<Tests>();
for (int i = 0; i < 4; i++)
{
    newTests.Add(myTests[myInt[i]]);
}
于 2012-12-06T13:03:28.150 に答える
0

初め:

myList[i]position でリストのアイテムを作成していないと使用できませんi

2番:

Tests新しいTestsオブジェクトを作成するためにコンストラクターを呼び出していません

三番:

myInt[i]空の参照に割り当てていますmyTests[i]

次のようなものが必要です。

for (int i = 0; i < 4; i++) {

    myTests.Add(new Tests(i, "foo"))

}
于 2012-12-06T13:03:56.467 に答える